tags:

views:

52

answers:

3

Hi, I would like to check if a string contains:

  • at least 1 number
  • at least 2 characters (uppercase or lowercase)

This is the regex I though I might use:

(?=(?:.*?\d))(?=(?:.*?[A-Za-z]){2})

With aa1 the test gives a false statement, while with a1a or 1aa it gives a true result.

The strange thing is that if I change the order of the controls in the regexp:

(?=(?:.*?[A-Za-z]){2})(?=(?:.*?\d))

all 3 of the test string I used wives a true value.

How is it possible?

Thanks

A: 

It is not strange. Your first regex checks if there is one number followed somewhere by 2 chars. The second one checks it in the other way. You need to take both cases in account.

Something like this should work (not tested)

/(\d(?:.*?)[a-z]{2})|([a-z]{2}(?:.*?)\d)/i
Benoit Vidis
Those are lookaheads. They do not consume characters and therefore match at the same position. Switching two consecutive lookaheads around should make no difference in the result (though may affect performance quite a bit).
Max Shawabkeh
A: 

Try this:

(?=\D*\d)(?=[^A-Za-z]*[A-Za-z][^A-Za-z]*[A-Za-z])

Or a little more compact:

(?=\D*\d)(?=(?:[^A-Za-z]*[A-Za-z]){2})
Gumbo
+1  A: 

You wouldn't happen to be writing this in JavaScript and testing in Internet Explorer, would you? That configuration has a known bug that causes this kind of error.

Alan Moore
You're right: I've tested regex with IE7. I found the recommended article very useful. Thanks.
CorPao