2012-04-19 64 views
1

我有以下正则表达式来检查密码策略。这是验证工作:将普通正则表达式转换为bash证明正则表达式

(^([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

无关你的问题:这是一个奇怪的密码策略。一组有效的密码以'z'开头,并且后面有三位数字?我的电话*可能会在几秒钟内破解:) – 2012-04-19 08:19:19

+0

@TimPietzcker我不是一个正则表达式专家,但它应该匹配策略'至少9个字符,并且每个4个字符类中至少有一个字符(字母大写,小写和大写;数字,符号)。“你说的没错,我应该纠正第一部分 – Michael 2012-04-19 08:25:04

+0

更糟糕的是:即使是空字符串也是有效的密码!我会为我的回答添加一个分析。 – 2012-04-19 08:32:05

回答

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].*$ 
+0

谢谢。如果我运行perl form bash,会更容易吗?另外,我需要对正则表达式做些什么修改?我仍然需要逃避特殊字符? – Michael 2012-04-19 08:01:53

+0

非常感谢您的见解。 – Michael 2012-04-19 08:45:22

相关问题