Bash 正则表达式匹配不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19327220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash regex matching not working
提问by pillarOfLight
so I have this function
所以我有这个功能
function test(){
local output="CMD[hahahhaa]"
if [[ "$output" =~ "/CMD\[.*?\]/" ]]; then
echo "LOOL"
else
echo "$output"
fi;
}
however executing test in command line would output $output instead of "LOOL" despite the fact that the pattern should be matching $output...
然而,尽管模式应该与 $output 匹配,但在命令行中执行测试将输出 $output 而不是“LOOL”...
what did I do wrong?
我做错了什么?
回答by Ravi Thapliyal
Don't use quotes ""
不要使用引号 ""
if [[ "$output" =~ ^CMD\[.*?\]$ ]]; then
Update :更新 :(in response to @frhd)(回应@frhd)
Well, the regex operator =~
expects an unquotedregular expression on its RHS and does only a sub-string match unless the anchors ^
(start of input) and $
(end of input) are also used to make it match the whole of the LHS.
好吧,正则表达式运算符=~
期望在其 RHS 上有一个不带引号的正则表达式,并且只进行子字符串匹配,除非还使用锚点^
(输入开始)和$
(输入结束)使其与整个 LHS 匹配。
Quotations""
override this behaviour and force a simple string match instead i.e. the matcher starts looking for all these characters \[.*?\]
literally.
引用""
会覆盖此行为并强制进行简单的字符串匹配,即匹配器开始\[.*?\]
逐字查找所有这些字符。