【问题标题】:Convert general regex to bash proof regex将通用正则表达式转换为 bash 证明正则表达式
【发布时间】:2012-04-19 07:49:15
【问题描述】:

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

(^([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 的正确方法是什么?还有什么需要注意的吗?

谢谢

【问题讨论】:

  • 与您的问题无关:这是一个奇怪的密码策略。一组有效的密码以z 开头,之后正好是三位数字?我的 手机 可以在几秒钟内破解 :)
  • @TimPietzcker 我不是正则表达式专家,但这应该符合at least 9 characters, with at least one character from each of the 4 character classes (alphabetic lower and upper case; numeric, symbols). 的政策,不过你是对的,我应该更正第一部分
  • 更糟糕的是:即使是空字符串也可以作为密码!我将在我的答案中添加分析。

标签: regex bash unix


【解决方案1】:

这可能很困难。

标准grep 功能有限。它仅支持无法识别您的正则表达式所依赖的 lookahead assertions 的 POSIX 扩展正则表达式。

如果您的机器上有 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].*$

【讨论】:

  • 谢谢。如果我从 bash 中运行 perl 会更容易吗?另外,我必须对正则表达式进行哪些修改?我仍然需要转义特殊字符吗?
  • 非常感谢您的见解。
猜你喜欢
  • 2011-10-02
  • 2016-04-02
  • 1970-01-01
  • 2019-05-11
  • 2014-11-08
  • 2017-12-29
  • 2023-03-09
  • 2013-06-26
相关资源
最近更新 更多