为什么这个匹配

[[ 'hithere' =~ hi* ]]

但这不是
[[ 'hithere' =~ *there ]]

最佳答案

=~特别是aregular expressions operator。如果要匹配零个或多个字符,则需要.*,而不仅仅是*

[[ 'hithere' =~ hi.* ]] && echo "Yes"
Yes

[[ 'hithere' =~ .*there ]] && echo "Yes"
Yes

不过,如果没有锚,即使没有通配符,匹配也会成功。
[[ 'hithere' =~ hi ]]
[[ 'hithere' =~ there ]]
# Add anchors to guarantee you're matching the whole phrase.
[[ 'hithere' =~ ^hi.*$ ]]
[[ 'hithere' =~ ^.*there$ ]]

对于模式匹配,可以对未引用的值使用=。它使用bash pattern matching代替,这正是您(显然)所期望的。
[[ 'hithere' = hi* ]] && echo "Yes"
Yes

[[ 'hithere' = *there ]] && echo "Yes"
Yes

10-07 22:31