0

I am using the following regular expression to confirm:

  • 2 letters in upper-case
  • 1 special character (in !@#$&*)
  • 2 numerals (09)
  • 3 letters in lower-case
^(?=.*[A-Z].*[A-Z])(?=.*[!@#$&*])(?=.*[0-9].*[0-9])(?=.*[a-z].*[a-z].*[a-z]).{8}$

And it works fine for the flowing password: AdiNm!15 but I don’t understand why I had to write .{8}. If I removed .{8} it is not working. But I don’t like to add restriction of string length. Any Idea?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Abdus Sattar Bhuiyan
  • 3,016
  • 4
  • 38
  • 72
  • Replace `{8}` with `*` (to match 0 or more chars) or `+` (to match 1 or more) – Wiktor Stribiżew Jul 31 '18 at 12:36
  • 1
    That's a very odd dupe. I think the question is more about understanding the `$` anchor. *That's* the reason why you need the `.{8}` or `.*` or `.+`, because it matches at the end of the string. – Aran-Fey Jul 31 '18 at 12:42
  • 1
    The core misunderstanding comes from the look-aheads `(?=`…`)`. They are zero-width assertions, meaning, they don’t consume characters. If you reduce your regex without the `.{8}` to only actually consumed characters, it would just be `^$`, which matches only empty strings. Since this contradicts any look-ahead assertions, the regex never matches anything. A more fitting dupe target is [Positive lookahead not working as expected](https://stackoverflow.com/q/31347686/4642212). – Sebastian Simon Jul 31 '18 at 12:45
  • You should read [Reference - Password Validation](https://stackoverflow.com/questions/48345922) – ctwheels Aug 21 '18 at 14:19

0 Answers0