开发者

Regex: change the order of the controls

开发者 https://www.devze.com 2022-12-20 08:54 出处:网络
I would like to check if a string contains: at least 1 number at least 2 characters (uppercase or lowercase)

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开发者_如何学Go string I used wives a true value.

How is it possible?

Thanks


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.


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


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})
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号