如何在ubuntu中的shell脚本中编写正则表达式断言

时间:2015-11-22 16:20:25

标签: linux bash shell ubuntu

以下是许多语言的有效正则表达式,但它在bash中不起作用:

((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})

如何在shell脚本中编写此正则表达式?

1 个答案:

答案 0 :(得分:1)

由于bash没有实现超前断言,您需要使用一个实用程序(例如,grep带有-P选项(如果在您的系统上可用),或者使用脚本语言,例如Perl或Python),或将其分解为不同的测试:

if [[ $pwd =~ [[:digit:]] &&
      $pwd =~ [[:upper:]] &&
      $pwd =~ [[:lower:]] &&
      $pwd =~ [@#$%] &&
      $pwd =~ ^.{6,20}$ ]]; then
    # $pwd satisfies all tests
else
    # $pwd fails some test
fi