Regex 正则表达式在if语句中将字符串与空格匹配(使用引号?)
我将如何进行如下所示的正则表达式匹配,但在“^This”周围加引号,就像在现实世界中一样,“This”将是一个可以包含空格的字符串Regex 正则表达式在if语句中将字符串与空格匹配(使用引号?),regex,linux,string,bash,debian,Regex,Linux,String,Bash,Debian,我将如何进行如下所示的正则表达式匹配,但在“^This”周围加引号,就像在现实世界中一样,“This”将是一个可以包含空格的字符串 #!/bin/bash text="This is just a test string" if [[ "$text" =~ ^This ]]; then echo "matched" else echo "not matched" fi 我想做一些像 if [[ "$text" =~ "^This is" ]]; then 但这不匹配。您是否尝
#!/bin/bash
text="This is just a test string"
if [[ "$text" =~ ^This ]]; then
echo "matched"
else
echo "not matched"
fi
我想做一些像
if [[ "$text" =~ "^This is" ]]; then
但这不匹配。您是否尝试过:
^[\s]*This
您可以在空格之前使用
\
#!/bin/bash
text="This is just a test string"
if [[ "$text" =~ ^This\ is\ just ]]; then
echo "matched"
else
echo "not matched"
fi
你能更清楚地描述你的问题吗
text="This is just a test string"
case "$text" in
"This is"*) echo "match";;
esac
以上假设您希望在行首匹配“This is”。我没有像这样内联表达式:
if [[ "$text" =~ "^ *This " ]]; then
pat="^ *This "
if [[ $text =~ $pat ]]; then
但如果将表达式放在变量中,则可以使用以下常规正则表达式语法:
if [[ "$text" =~ "^ *This " ]]; then
pat="^ *This "
if [[ $text =~ $pat ]]; then
请注意,$text
和$pat
上的引用是不必要的
编辑:
在开发过程中,一款方便的oneliner:
pat="^ *This is "; [[ " This is just a test string" =~ $pat ]]; echo $?
+1这绝对是做这件事的方法。与
=~
一起使用的Bash正则表达式应该经常(总是?)是不带引号的。这很好。我以前从未使用过bash正则表达式,我只是尝试了一下,发现它有效。在S.O.上,除非证明错误,否则它是正确的!FWIW,这在Bash3.1和Bash3.2之间发生了变化。Bash 4.0有一个可配置的shopt-s/-u compat31
来在行为之间切换。在$text
的开头没有空格,因此$pat
应该是“^This”
。此外,在这里引用变量不仅是不必要的,而且是行不通的+1用于显示变量格式。