我是regex的新手,并试图创建一个正则表达式来验证密码短语。我想验证密码短语:
这就是我到目前为止所拥有的
^(?=.*?((?:.*?\b[a-zA-Z0-9]{2,40}\b)\s*){3,})(?=.*?[@#$%^&+=])(?=.*?[0-9]).*$
它匹配此Pe2sI#sHy?ThYulU#
短语,该短语至少有3个单词(无空格)。我究竟做错了什么?
答案 0 :(得分:3)
您应该使用\s+
代替\s*
。后者允许零空间,前者需要至少一个。但你的正则表达式过于复杂。试试这个:
^ # Start of string
(?=.*\d) # Assert at least one digit
(?=.*[@#$%^&+=]) # Assert at least one special char
\s* # Optional leading whitespace
(?: # Match...
\S{2,} # at least 2 non-spaces
\s+ # at least 1 whitespace
){2,} # at least 2 times
\S{2,} # Match at least 2 non-spaces (making 3 "words" minimum)
答案 1 :(得分:2)
有点晚了,所以这只是观察。
这是@Tim Pietzcker方法的起飞 虽然'单词'可以是任何东西,但如果你想要至少为什么 3个字有[a-zA-Z0-9] {2,40}个字符嵌入,你可以这样做。
^ # String start
(?=.*[@#$%^&+=]) # Assert 1 special char
(?=.*\d) # Assert 1 digit
(?: # Special 'Word Group' -- Need 2 words
.* # Any char, 0 or more times
[a-zA-Z0-9]{2,40} # Alpha/num char, 2 to 40 times
.* # Any char, 0 or more times
\s # a whitespace, only 1 required
){2} # 'Word Group' end, do 2 times
.* # Any char, 0 or more times
[a-zA-Z0-9]{2,40} # Alpha/num char, 2 to 40 times -- Need 1 word
这应至少匹配至少3个特殊的[a-zA-Z0-9] {2,40}单词,至少间隔1个空格
包括数字和特殊字符。
更新
是的,您可以通过我知道的两种方式将它组合成一个组{3}次。
使用捕获缓冲区作为标记
^(?=.*[@#$%^&+=])(?=.*\d)(?:(?:(?!\1)|\s).*[a-zA-Z0-9]{2,40}().*){3}
^ ^
---------------------------------------
^ # String start
(?=.*[@#$%^&+=]) # Assert 1 special char
(?=.*\d) # Assert 1 digit
(?: # Special 'Word Group'
(?: #.. grping start ....
(?!\1) # Either capt group 1 is UN-DEFINED
| \s # OR, require a whitespace
) #.. grping end ....
.* # Any char, 0 or more times
[a-zA-Z0-9]{2,40} # Alpha/num char, 2 to 40 times
() # DEFINE Capture group 1
.* # Any char, 0 or more times
){3} # 'Word Group' end, do 3 times
或者,使用条件
^(?=.*[@#$%^&+=])(?=.*\d)(?:(?(1)\s).*([a-zA-Z0-9]{2,40}).*){3}
^ ^
---------------------------------------
^ # String start
(?=.*[@#$%^&+=]) # Assert 1 special char
(?=.*\d) # Assert 1 digit
(?: # Special 'Word Group'
(?(1)\s) # Conditional, require a whitespace if capture group 1 captured anything
.* # Any char, 0 or more times
([a-zA-Z0-9]{2,40}) # Capture group 1, Alpha/num char, 2 to 40 times
.* # Any char, 0 or more times
){3} # 'Word Group' end, do 3 times