Bash正则表达式匹配不起作用 [英] Bash regex matching not working
问题描述
所以我有这个功能
function test(){
local output="CMD[hahahhaa]"
if [[ "$output" =~ "/CMD\[.*?\]/" ]]; then
echo "LOOL"
else
echo "$output"
fi;
}
尽管模式应该与$ output相匹配,但是在命令行中执行测试会输出$ output而不是"LOOL" ...
however executing test in command line would output $output instead of "LOOL" despite the fact that the pattern should be matching $output...
我做错了什么?
推荐答案
请勿使用引号""
if [[ "$output" =~ ^CMD\[.*?\]$ ]]; then
更新: (响应@frhd)
好吧,正则表达式运算符=~
在其RHS上期望 unquoted 正则表达式,并且仅执行子字符串匹配,除非锚点^
(输入的开始)和$
(输入的末尾)还用于使其与整个LHS匹配.
Well, the regex operator =~
expects an unquoted regular 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.
报价 ""
会覆盖此行为,而是强制进行简单的字符串匹配,即匹配器从字面上查找所有这些字符\[.*?\]
.
Quotations ""
override this behaviour and force a simple string match instead i.e. the matcher starts looking for all these characters \[.*?\]
literally.
这篇关于Bash正则表达式匹配不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!