Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
所以我有这个功能
function test(){ local output="CMD[hahahhaa]" if [[ "$output" =~ "/CMD\[.*?\]/" ]]; then echo "LOOL" else echo "$output" fi; }
然而,在命令行中执行测试会输出 $output 而不是“LOOL”,尽管模式应该匹配 $output...
我做错了什么?
不要使用引号""
""
if [[ "$output" =~ ^CMD\[.*?\]$ ]]; then
正则表达式运算符=~期望在其 RHS 上使用不带引号的正则表达式,并且只匹配子字符串,除非锚^(输入开始)和$(输入结束)也用于使其匹配整个 LHS。
=~
^
$
引号 ""会覆盖此行为并强制进行简单的字符串匹配,即匹配器开始\[.*?\]逐字查找所有这些字符。
\[.*?\]