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

非 Y 不嫁゛ 提交于 2019-12-21 07:17:11

问题


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.

#!/bin/bash

text="This is just a test string"
if [[ "$text" =~ ^This ]]; then
 echo "matched"

else
 echo "not matched"
fi

I want to do something like

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

but this doesn't match.


回答1:


You can use \ before spaces.

#!/bin/bash

text="This is just a test string"
if [[ "$text" =~ ^This\ is\ just ]]; then
  echo "matched"
else
  echo "not matched"
fi



回答2:


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 $?



回答3:


can you make your problem description clearer?

text="This is just a test string"
case "$text" in
    "This is"*) echo "match";;
esac

the above assume you want to match "This is" at exactly start of line.




回答4:


Have you tried:

^[\s]*This


来源:https://stackoverflow.com/questions/1599103/regex-match-a-string-with-spaces-use-quotes-in-an-if-statement

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