Bash regex matching not working [duplicate]

。_饼干妹妹 提交于 2019-12-23 07:29:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!