Ghos3t
Ghos3t

Reputation: 203

Regular Expression Range not working as intended for verifying randomly generated passwords

I am trying to verify passwords generated using a random password generator function by using regular expression in C++.

the rules for the passwords are: The password has to be 8 letters total length. the password can be 4 capital alphabets and 4 numbers or 6 capital alphabets and 2 numbers.

Valid Examples:

I am using this expression: /^(?=.{8}$)([A-Z]{4,6})([0-9]{2,4})\w+/gm

and this website to test the expression: http://regexr.com/3frd4

it works when the range is kept as {1,4} but if I change the range to {2,4} the second example password fails.

Clicking on the details button shows that for the first example password: ABCD1234,

Capturing Group #1 captures ABCD & Capturing Group #2 captures only 123 (not 1234?).

For the second example password: PQRSTU88,

Capturing Group #1 captures PQRSTU & Capturing Group #2 captures only 8 (not 88?).

from what I understand {2,4} specifies at least 2 numbers to at most 4 numbers. Then why is my regex not working for that range in case of the second example.

Upvotes: 1

Views: 56

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627302

Your second string fails the validation as it contains 5 letters and 2 digits only, but your regex requires at least 1 more word char after them.

The password has to be 8 letters total length. the password can be 4 capital alphabets and 4 numbers or 6 capital alphabets and 2 numbers.

You need to use

^(?:[A-Z]{4}[0-9]{4}|[A-Z]{6}[0-9]{2})$

See the regex demo.

Details:

  • ^ - start of string
  • (?: - alternation group start
    • [A-Z]{4} - 4 uppercase ASCII letters
    • [0-9]{4} - 4 digits (8 all in all)
  • | - or
    • [A-Z]{6} - 6 uppercase ASCII letters
    • [0-9]{2} - 2 digits (8 all in all)
  • ) - end of an alternation group
  • $ - end of string.

Upvotes: 2

Related Questions