正则表达式在if语句中匹配带空格的字符串(使用引号?)

时间:2009-10-21 06:46:58

标签: 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

但这不匹配。

4 个答案:

答案 0 :(得分:20)

您可以在空格之前使用\

#!/bin/bash

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

答案 1 :(得分:0)

我没有设法像这样内联表达式:

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

但如果将表达式放在变量中,则可以使用正常的正则表达式语法,如下所示:

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

请注意,$text$pat上的引用是无关紧要的。

修改 在开发过程中一个方便的oneliner:

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

答案 2 :(得分:-1)

你能让你的问题描述更清楚吗?

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

以上假设您希望在行的开头匹配“This is”。

答案 3 :(得分:-2)

你试过了吗?

^[\s]*This