Regex match a string with spaces (use quotes?) in an if statement

后端 未结 4 1320
情书的邮戳
情书的邮戳 2021-02-19 11:05

How would I do a regex match as shown below but with quotes around the (\"^This\") as in the real world \"This\" will be a string that can have spaces in it.

#!/         


        
4条回答
  •  南方客
    南方客 (楼主)
    2021-02-19 11:30

    I did not manage to inline the expression like this:

    if [[ "$text" =~ "^ *This " ]]; then
    

    but if you put the expression in a variable you could use normal regex syntax like this:

    pat="^ *This "
    if [[ $text =~ $pat ]]; then
    

    Note that the quoting on $text and $pat is unnessesary.

    Edit: A convinient oneliner during the development:

    pat="^ *This is "; [[ "   This is just a test string" =~ $pat ]]; echo $?
    

提交回复
热议问题