什么是正则表达式以确保给定字符串包含来自以下每个类别的至少一个字符.
我知道各组分别是模式[a-z],[A-Z],\d和_|[^\w](我让他们正确的,不是吗?).
但是我如何组合它们以确保字符串以任何顺序包含所有这些?
Bar*_*ers 325
如果您需要一个正则表达式,请尝试:
(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*\W)
Run Code Online (Sandbox Code Playgroud)
一个简短的解释:
(?=.*[a-z]) // use positive look ahead to see if at least one lower case letter exists
(?=.*[A-Z]) // use positive look ahead to see if at least one upper case letter exists
(?=.*\d) // use positive look ahead to see if at least one digit exists
(?=.*\W]) // use positive look ahead to see if at least one non-word character exists
Run Code Online (Sandbox Code Playgroud)
我同意SilentGhost,\W可能有点宽泛.我用这样的字符集替换它:( [-+_!@#$%^&*.,?]当然可以添加更多!)
Jua*_*ini 15
Bart Kiers,你的正则表达式有几个问题.最好的方法是:
(.*[a-z].*) // For lower cases
(.*[A-Z].*) // For upper cases
(.*\d.*) // For digits
Run Code Online (Sandbox Code Playgroud)
无论是在开头,结尾还是在中间,你都会以这种方式进行搜索.你有我复杂的密码有很多麻烦.
Ens*_*ado 13
Bart Kiers 解决方案很好,但它错过了拒绝包含空格的字符串和接受包含下划线( _) 作为符号的字符串。
改进 Bart Kiers 解决方案,下面是正则表达式:
(?=.*\d)(?=.*[a-z])(?=.*[A-Z])((?=.*\W)|(?=.*_))^[^ ]+$
简短的解释:
(?=.*[a-z]) // use positive look ahead to see if at least one lower case letter exists
(?=.*[A-Z]) // use positive look ahead to see if at least one upper case letter exists
(?=.*\d) // use positive look ahead to see if at least one digit exists
(?=.*\W) // use positive look ahead to see if at least one non-word character exists
(?=.*_) // use positive look ahead to see if at least one underscore exists
| // The Logical OR operator
^[^ ]+$ // Reject the strings having spaces in them.
Run Code Online (Sandbox Code Playgroud)
旁注:您可以在此处尝试正则表达式的测试用例。