RegEx以确保该字符串包含至少一个小写字母char,大写字母char,数字和符号

Ama*_*osh 144 regex

什么是正则表达式以确保给定字符串包含来自以下每个类别的至少一个字符.

  • 小写字符
  • 大写字母
  • 数字
  • 符号

我知道各组分别是模式[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可能有点宽泛.我用这样的字符集替换它:( [-+_!@#$%^&*.,?]当然可以添加更多!)

  • @ikertxu,尝试这样的事:`^(?=.*[az])(?=.*[AZ])(?=.*\d)(?!.*[&%$]).{6 ,} $` (4认同)

Jua*_*ini 15

Bart Kiers,你的正则表达式有几个问题.最好的方法是:

(.*[a-z].*)       // For lower cases
(.*[A-Z].*)       // For upper cases
(.*\d.*)          // For digits
Run Code Online (Sandbox Code Playgroud)

无论是在开头,结尾还是在中间,你都会以这种方式进行搜索.你有我复杂的密码有很多麻烦.

  • 您没有像OP请求的那样检查符号. (5认同)
  • 仅当按此顺序找到小写字母、大写字母和数字时,这才会起作用。例如,ist 不适用于 111aaqBBB (2认同)

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)

旁注:您可以在此处尝试正则表达式的测试用例。

  • 为什么要拒​​绝太空?如果这是密码,则根据 [OWASP 建议](https://owasp.org/www-community/password-special-characters) 还应包含空格 (2认同)

Sil*_*ost 5

您可以分别匹配这三个组,并确保它们都存在.此外,[^\w]似乎有点过于宽泛,但如果这是你想要的,你可能想要替换它\W.