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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1599103/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 21:18:15  来源:igfitidea点击:

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

regexlinuxstringbashdebian

提问by Mint

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.

我将如何进行如下所示的正则表达式匹配,但在 ("^This") 周围加上引号,就像在现实世界中一样,"This" 将是一个可以包含空格的字符串。

#!/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.

但这不匹配。

回答by too much php

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

回答by UlfR

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 $textand $patis unnessesary.

请注意,引用$text$pat是不必要的。

Edit:A convinient oneliner during the development:

编辑:开发过程中方便的oneliner:

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

回答by ghostdog74

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.

以上假设您想在行首匹配“This is”。

回答by Kshitij Saxena -KJ-

Have you tried:

你有没有尝试过:

^[\s]*This