Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash regex matching not working [duplicate]

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?

like image 697
pillarOfLight Avatar asked Oct 11 '13 21:10

pillarOfLight


1 Answers

Don't use quotes ""

if [[ "$output" =~ ^CMD\[.*?\]$ ]]; then

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.

like image 170
Ravi K Thapliyal Avatar answered Oct 16 '22 05:10

Ravi K Thapliyal