我需要一个正则表达式的帮助,包括1个或更多个小写字母,1个或更多个大写字母,1个或更多个数字,以及正好1个特殊字符。
到目前为止我写了这个:
^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[\@\#\^])[a-zA-Z0-9\@\#\^]*$
它有多个特殊字符。 顺便说一句,我使用grep -P,并且我首先使用http://regexr.com/测试我的正则表达式。
我忘了提到角色应该是任何顺序。
答案 0 :(得分:2)
将您的特殊字符分隔为仅匹配一次的不同字符类:
^(?=.*\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
这比原作更好,因为它确保匹配一个且只有一个特殊字符