问题
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...
what did I do wrong?
回答1:
Don't use quotes ""
if [[ "$output" =~ ^CMD\[.*?\]$ ]]; then
Update : (in response to @frhd)
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.
来源:https://stackoverflow.com/questions/19327220/bash-regex-matching-not-working