我有以下正则表达式来检查密码策略。它经过验证可以工作:
(^([zZ]\d{3})*$)|((?=.{9,})(?=.*?[^\w\s])(?=.*?[0-9])(?=.*?[A-Z]).*?[a-z].*)
我想在bash脚本中使用正则表达式,以下列方式验证psssword:
echo $password | grep "(^([zZ]\d{3})*$)|((?=.{9,})(?=.*?[^\w\s])(?=.*?[0-9])(?=.*?[A-Z]).*?[a-z].*)"
if [[ $? -eq 0 ]] ; then
这在bash中不起作用。 我的问题是:
如何将这个“纯”正则表达式转换为一个在bash中运行的正则表达式?我需要逃避哪些角色,将正则表达式传递给grep的正确方法是什么?还有其他我需要注意的事情吗?
由于
答案 0 :(得分:2)
这可能很难。
标准grep
功能有限。它只支持POSIX扩展正则表达式,它不能识别你的正则表达式所依赖的lookahead assertions。
如果你的计算机上有GNU grep
,你可以传递-P
或--perl-regexp
参数,允许它使用Perl兼容的正则表达式。然后你的正则表达式应该工作。
正如我的评论中所提到的,正则表达式不适用于密码验证。它允许使用z000
之类的密码,甚至是空字符串:
( # Either match and capture...
^ # Start of the string
( # Match (and capture, uselessly in this case)
[zZ] # case-insensitive z
\d{3} # three digits
)* # zero(!) or more times
$ # until the end of the string
) # End of first group.
| # OR
( # match and capture...
(?=.{9,}) # a string that's at least 9 characters long,
(?=.*?[^\w\s]) # contains at least one non-alnum, non-space character,
(?=.*?[0-9]) # at least one ASCII digit
(?=.*?[A-Z]) # at least one ASCII uppercase letter
.*?[a-z].* # and at least one ASCII lowercase letter
) # no anchor to start/end of string...
更好地使用
^(?=.{9})(?=.*?[^\w\s])(?=.*?[0-9])(?=.*?[A-Z]).*?[a-z].*$