I have a very basic regular expression that I just can't figure out why it's not working so the question is two parts. Why does my current version not work and what is the correct expression.
Rules are pretty simple:
- Must have minimum 3 characters.
- If a % character is the first character must be a minimum of 4 characters.
So the following cases should work out as follows:
- AB - fail
- ABC - pass
- ABCDEFG - pass
- % - fail
- %AB - fail
- %ABC - pass
- %ABCDEFG - pass
- %%AB - pass
The expression I am using is:
^%?\S{3}
Which to me means:
^
- Start of string%?
- Greedy check for 0 or 1 % character\S{3}
- 3 other characters that are not white space
The problem is, the %?
for some reason is not doing a greedy check. It's not eating the % character if it exists so the '%AB' case is passing which I think should be failing. Why is the %?
not eating the % character?
Someone please show me the light :)
Edit: The answer I used was Dav below: ^(%\S{3}|[^%\s]\S{2})
Although it was a 2 part answer and Alan's really made me understand why. I didn't use his version of ^(?>%?)\S{3}
because it worked but not in the javascript implementation. Both great answers and a lot of help.