将通用正则表达式转换为 bash 证明正则表达式



我有以下正则表达式来检查密码策略。 它经过验证可以正常工作:

(^([zZ]d{3})*$)|((?=.{9,})(?=.*?[^ws])(?=.*?[0-9])(?=.*?[A-Z]).*?[a-z].*)

我想在 bash 脚本中使用正则表达式来通过以下方式验证 psssword :

echo $password | grep "(^([zZ]d{3})*$)|((?=.{9,})(?=.*?[^ws])(?=.*?[0-9])(?=.*?[A-Z]).*?[a-z].*)"
if [[ $? -eq 0 ]] ; then

这在 bash 中不起作用。我的问题是:

如何将这个"纯"正则表达式转换为在 bash 中工作的正则表达式? 我需要转义哪些字符,将正则表达式传递给 grep 的正确方法是什么? 还有其他需要注意的事情吗?

谢谢

这可能

很困难。

标准grep的功能有限。它仅支持 POSIX 扩展正则表达式,这些表达式无法识别正则表达式所依赖的前瞻断言。

如果你的机器上有GNU grep,你可以给它传递-P--perl-regexp参数,允许它使用与Perl兼容的正则表达式。那么你的正则表达式应该可以工作了。

正如我在评论中提到的,正则表达式原样不适合 passwort 验证。它允许像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,
  (?=.*?[^ws])  #  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})(?=.*?[^ws])(?=.*?[0-9])(?=.*?[A-Z]).*?[a-z].*$

最新更新