tags:

views:

78

answers:

3

How do I use lookahead assertion to determine if a certain character exist at most a certain number of times in a string.

For example, let's say I want to check a string that has at least one character to make sure that it contains "@" at most 2 times. Thanks in advance. Using python if that matters.

+4  A: 

There are lots of ways to do this, for example:

/^(?=([^@]*@){,2}[^@]*$)./
Mark Byers
Nicely optimized too..
gnarf
Thanks! How does your answer differ from this: (?=[^@]*[@]{,2}[^@]*$)
teggy
@teggy: In your version, the quantifier `{,2}` applies only to the immediately preceding atom, `[@]`, so it will match `xx@@xx` but not `xx@xx@xx`.
Alan Moore
not working. I am using JavaScript. text = 'aa@@';regex = /^(?=([^@]*@){,2}[^@]*$)./console.log(text.match(regex));
Nadal
@dorelal: This is a question for Python not Javascript. For Javascript you need to write {0,2} instead of {,2}.
Mark Byers
A: 

Using a negative lookahead assertion, you can make sure that @ doesn't occur three times:

(?!.*@.*@.*@.*).*
Kaleb Pederson
A: 

I believe Mark's answer wont quite work as you need to exclude the @ from being matched at other times. Try this:

^(?=(([^@]*@){0,2}[^@]*$))

Edit: Mark fixed his answer, ours should be the same now. Also, fixed.

David Kanarek
Your lookahead should be anchored like Mark's.
Alan Moore
not working. I am using JavaScript. text = 'aa@@';regex = /^(?=(([^@]*@){,2}[^@]*$))/console.log(text.match(regex));
Nadal