我正在尝试检查给定字符串中是否包含 .rel6.
。我对 Bash 正则表达式的行为有点困惑。我在这里缺少什么?
os=$(uname -r) # set to string "2.6.32-504.23.4.el6.x86_64"
[[ $os =~ *el6* ]] && echo yes # doesn't match, I understand it is Bash is treating it as a glob expression
[[ $os =~ el6 ]] && echo yes # matches
[[ $os =~ .el6 ]] && echo yes # matches
[[ $os =~ .el6. ]] && echo yes # matches
[[ $os =~ ".el6." ]] && echo yes # matches
[[ $os =~ *".el6." ]] && echo yes # * does not match - why? *
[[ $os =~ ".el6."* ]] && echo yes # matches
re='\.el6\.'
[[ $os =~ $re ]] && echo yes # matches
特别是这个:
[[ $os =~ *".el6." ]] && echo yes
最佳答案
=~
运算符对其左侧的字符串和右侧的表达式模式执行正则表达式匹配操作。因此,这里所有的 RHS 都是正则表达式模式。
[[ $os =~ *el6* ]] && echo yes
不匹配,因为正则表达式为 *el6*
和 *
是一个量词,但您无法量化正则表达式的开头,因此它是无效的正则表达式。请注意,[[ $os =~ el6* ]] && echo yes
将打印 yes
因为 el6*
与 el
匹配> 和 0+ 6
秒。
[[ $os =~ *".el6"也存在类似问题。 ]] && echo yes
:正则表达式是*.el6.
,并且它是无效的。
如果您想检查 .el6.
是否在字符串中,请使用 [[ $os = *".el6."* ]] && echo yes
。在这里,全局模式将为 *.el6.*
并且您需要 =
运算符。
关于与通配符匹配的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49019795/