Reputation: 77
I need help with a Regex for 1 or more lowercase letters, 1 or more uppercase letters , 1 or more digits, and exactly 1 special character.
I wrote this so far:
^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[\@\#\^])[a-zA-Z0-9\@\#\^]*$
It gets more than one special character. By the way I'm using grep -P, and I'm testing my regex's with http://regexr.com/ first.
I forgot to mention that the characters should be in any order.
Upvotes: 1
Views: 1495
Reputation: 5515
separate your special characters to a different character class that only matches once:
^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9]*[\@\#\^][a-zA-Z0-9]*$
#NOTES: ^you dont need to do a look ahead for the special char since you explicitly match only 1
(?=...) ... ) signifies lookaheads: they each check that there is at least
one number, lowercase, and uppercase letter in the following match
[a-zA-Z0-9]* matches 0 or more of those for as long as possible
[\@\#\^] matches exactly one of these characters
[a-zA-Z0-9]* matches any of the remaining characters
this works better than the original because it ensures that one, and only one, special character is matched
Upvotes: 2