正则表达式与通配符匹配
Regex matching with a wildcard
我正在尝试检查给定字符串中是否包含 .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
s.
[[ $os =~ *".el6." ]] && echo yes
也有类似的问题:正则表达式是 *.el6.
,它是无效的。
如果要检查 .el6.
是否在字符串中,请使用 [[ $os = *".el6."* ]] && echo yes
。此处,glob 模式将为 *.el6.*
并且您需要 =
运算符。
我正在尝试检查给定字符串中是否包含 .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
s.
[[ $os =~ *".el6." ]] && echo yes
也有类似的问题:正则表达式是 *.el6.
,它是无效的。
如果要检查 .el6.
是否在字符串中,请使用 [[ $os = *".el6."* ]] && echo yes
。此处,glob 模式将为 *.el6.*
并且您需要 =
运算符。