确保给定字符串至少包含以下每一类别中的一个字符的正则表达式是什么。
- 小写字符
- 大写字符
- 数字
- 符号
我知道各个集合的模式,即 [a-z]
、[A-Z]
、\d
和 _|[^\w]
(我猜对了,不是吗?)。
但是如何将它们组合起来以确保字符串以任意顺序包含所有这些内容?
最佳答案
如果您需要一个正则表达式,请尝试:
(?=.*\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
我同意 SilentGhost 的观点,\W
可能有点宽泛。我将其替换为如下字符集:[-+_!@#$%^&*.,?]
(当然可以随意添加更多内容!)
关于RegEx 确保字符串至少包含一个小写字符、大写字符、数字和符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58869206/