-1

What the difference between

(?=.\d)(?=.[a-z])(?=.[A-Z]) 

and

(.\d)(.[a-z])(.[A-Z])

When I test the string a2A only the first RegExp returns true. Can anyone explain this for me?

Tim Biegeleisen
  • 387,723
  • 20
  • 200
  • 263
VN Pikachu
  • 9
  • 1
  • 3

1 Answers1

1

The difference is in the lookahead operator for each of the terms in the regex. The LA operator matches the sub-regex it guards as usual, but effectively locks the initial matching position for the subsequent regex portion.

This means that the first regex should not match (contrary to your tests, which engine have you used ?) - Given any initial matching position, the second character would have to be a number, a lowercase letter, and an uppercase letter, all at the same time.

Observe that this will not happen if the . ('any char') is quantified:

(?=.*\d)(?=.*[a-z])(?=.*[A-Z]) 

Each LA term may skip an arbitrary amount of material before matching the character class, and this amount may differ between the subexpressions.

The second alternative (with and without quantification) will never match as it invariably requires a subsequence of digit-letter-letter, which the test string a2A does not provide.

collapsar
  • 15,446
  • 3
  • 28
  • 56
  • Yep.It is (?=.*\d)(?=.*[a-z])(?=.*[A-Z]).But I write it to (?=.\d)(?=.[a-z])(?=.[A-Z]) .It's my mistake.So if i use (?=1)(?=2) what will fullfill this.The String "12" does not match that. – VN Pikachu Feb 03 '18 at 13:08
  • `(?=1)(?=2)` will never match by essentially the same reasoning: At a given matching position, the ne`xt character had to be a `1`and a `2`, simultaneuosly. – collapsar Feb 03 '18 at 13:53
  • Thanks.It helps me a lot. – VN Pikachu Feb 04 '18 at 03:45