I'm trying to create a regex to pattern match (for passwords) where the string must be between 8 and 30 characters, must have at least 2 digits, at least 2 letters (case-insensitive),at least 1 special character, and no spaces.
I've got the spaces and special character matching working, but am getting thrown on the 2 digits and 2 letters because they don't need to be consecutive.
i.e. it should match a1b2c$
or ab12$
or 1aab2c$
.
Something like this for the letters?
(?=.*[a-zA-Z].*[a-zA-Z]) // Not sure.
This string below works, but only if the 2 letters are consecutive and the 2 numbers are consecutive..it fails if the letters, numbers, special chars are interwoven.
(?=^.{8,30}$)((?=.*\\d)(?=.*[A-Za-z]{2})(?=.*[0-9]{2})(?=.*[!@#$%^&*?]{1})(?!.*[\\s]))^.*
?= is a positive lookahead, a type of zero-width assertion. What it's saying is that the captured match must be followed by whatever is within the parentheses but that part isn't captured. Your example means the match needs to be followed by zero or more characters and then a digit (but again that part isn't captured).
Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.
To solve my problem I just tried this regex: "\d{1}[A-Z]{1}\d{1}" but it extract 9A1 or 9C1 given examples strings here above. You should be able to use a capture group to extract the letter you need.
If you don't want letters to have to be consecutive (?=.*[a-zA-Z].*[a-zA-Z])
is correct approach. Same goes to digits (?=.*\\d.*\\d)
or (?=(.*\\d){2})
.
Try this regex
(?=^.{8,30}$)(?=(.*\\d){2})(?=(.*[A-Za-z]){2})(?=.*[!@#$%^&*?])(?!.*[\\s])^.*
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With