2015-09-30 57 views

回答

5

=~具体为regular 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 
+0

谢谢,这有助于澄清完美。我期待使用bash模式匹配,而是使用正则表达式运算符。 – quickshiftin

+3

请注意'[[hithere =〜* there]]的退出状态为2(不是1),表示正则表达式格式错误,而不是简单的匹配失败。 – chepner

+0

你有代理帮我添加数据库过滤支持到我的小mysqldump包装,[mysqlbkup](https://github.com/quickshiftin/mysqlbkup),所以谢谢你!增加了对BASH模式匹配和POSIX Regex的支持;) – quickshiftin

2

对于基本正则表达式

前述*只是一个字符,不被认为是正则表达式的特殊字符。

'*' 是一个普通的字符,如果它出现在RE的开始

Sourcehttp://man7.org/linux/man-pages/man7/regex.7.html


由杰夫·鲍曼回答的作品,因为

[[ 'hithere' =~ .*there ]] && echo "Yes"有是*之前的.