[英]Regex: Optional special characters
I have a regex which has the following rules:我有一个正则表达式,它具有以下规则:
+ Must contain lower case letters
+ Must contain upper case letters
+ Must contain a number
+ Must contain a (defined)special character
+ At least 8 chars
This works and my regex looks like this:这有效,我的正则表达式如下所示:
((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[~@#\$%\^&\*_\-\+=`|{}:;!\.\?\"()\[\]]).{8,25})
Now I want to change that regex in only one single thing: The special characters should still be possible (and only those I allow), but should be optional (not required anymore) anywhere in the string.现在我只想在一件事情上改变这个正则表达式:特殊字符应该仍然是可能的(并且只有我允许的那些),但应该是可选的(不再需要)字符串中的任何地方。 So the new rule would be
所以新规则是
+ MAY contain (defined) special characters
What do I have to change to achieve this?我必须改变什么才能实现这一目标?
Examples:例子:
NicePassw0rd - NOT OK now, should be
NicePassw0rd%% - OK now (and still should be)
NicePassword - NOT OK now and shouldnt
You can test my regex there: https://regex101.com/r/qN5dN0/1您可以在那里测试我的正则表达式: https : //regex101.com/r/qN5dN0/1
You must add anchors ^
and $
on both ends of the pattern to really enable length checking.您必须在模式的两端添加锚点
^
和$
才能真正启用长度检查。 If you want to disallow other special characters, move ~@#$%^&*+=`|{}:;!.?\\"()\\[\\]-
to the consuming part with letters and digits (note that [A-Za-z0-9_]
is the same as \\w
if you are using PCRE without /u
flag):如果要禁止其他特殊字符,请将
~@#$%^&*+=`|{}:;!.?\\"()\\[\\]-
到带有字母和数字的消耗部分(注意[A-Za-z0-9_]
与\\w
相同,如果您使用没有/u
标志的 PCRE):
^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[\w~@#$%^&*+=`|{}:;!.?\"()\[\]-]{8,25}$
See regex demo见正则表达式演示
Here is what it does:这是它的作用:
^
- start of string ^
- 字符串的开始(?=.*\\d)
- require at least one digit (?=.*\\d)
- 至少需要一位数字(?=.*[az])
- require at least a lowercase ASCII letter (?=.*[az])
- 至少需要一个小写的 ASCII 字母(?=.*[AZ])
- require at least 1 ASCII uppercase letter (?=.*[AZ])
- 至少需要 1 个 ASCII 大写字母[\\w~@#$%^&*+=`|{}:;!.?\\"()\\[\\]-]{8,25}
- match (=consume) 8 to 25 only symbols that are either alphanumeric, or _
, or all those inside the character class [\\w~@#$%^&*+=`|{}:;!.?\\"()\\[\\]-]{8,25}
- 仅匹配(=消耗)8 到 25 个符号字母数字或_
,或字符类中的所有字符$
- end of string $
- 字符串结尾A more efficient would be a regex based on contrast principle within lookaheads when we check for 0 or more characters other than those we need to check for presence and then the required symbol.当我们检查 0 个或更多字符而不是需要检查存在性和所需符号的字符时,基于前瞻中的对比原理的正则表达式将更有效。 See a corrected regex containing
(?=\\D*\\d)(?=[^az]*[az])(?=[^AZ]*[AZ])
:查看包含
(?=\\D*\\d)(?=[^az]*[az])(?=[^AZ]*[AZ])
的更正正则表达式:
^(?=\D*\d)(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z])[\w~@#$%^&*+=`|{}:;!.?\"()\[\]-]{8,25}$
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.