View Full Version : Problem with regular expression

14 Feb 2012, 7:43 AM

My password string has to have at least three digits. I wanted to use (?=.*[0-9]{3,}) expression but i faced the problem: this expression makes password string to have at least three digits together. I mean "1pass33", for example, doesn't satisfy the requirement. Is it possible to make such regex, that mixed string like my password will satisfy it?

Thanks a lot!

Colin Alworth
14 Feb 2012, 9:13 AM
Look for any data between the numbers as well. Untested:

This will require at least three numbers [0-9] each, and will allow some content between each one. Ideally the . would be replaced by something that can use the * greedy operator instead of the non-greedy *?, like [^0-9].

It should be possible to use the {3,} operator to repeat parts of the content, once it makes sense, and if it can be cleaned up.

15 Feb 2012, 12:40 AM
Thanx a lot!
(?=.*[0-9].*[0-9].*[0-9] ) Works great! :))
But isn't there any standart expression? I mean, if my password requires, let's say, at least 3 digits, at least 3 upper letters and at least 5 lower letters, looking for the characters with this method will make a regular expression string too long...

15 Feb 2012, 3:29 AM
Have found it.
(?=(.*[0-9].*){3,}) is shorter and works similar

Colin Alworth
15 Feb 2012, 7:12 AM
Regular expressions are good at what they do, which doesn't include everything - see for example this SO post on why regex might not be ideal for parsing html strings: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 Besides the humorous aspects, they do get to discuss why a regular expression might not be a good solution for that problem.

In your case, with multiple counters to maintain (upper, lower, numbers), the regex will have to be fairly in-depth to cover all these cases. Consider instead creating a Validator for the field, and use multiple very simple regexes to match the contents, as well as perhaps some other simple checks. A Validator even lets you return a string specific to what the user hasn't done right.

16 Feb 2012, 12:51 AM
Thanks for replying, the post is very useful. By the way, I've found useful page for regexes: rubular.com