正则表达式中的if语句匹配空格的字符串(用引号?) [英] Regex match a string with spaces (use quotes?) in an if statement

查看:628
本文介绍了正则表达式中的if语句匹配空格的字符串(用引号?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

会怎么做一个正则表达式匹配如下,但周围的报价显示的(^本)作为在现实世界这将是可以有空格在它的字符串。

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.

推荐答案

您可以使用 \\ 之前的空格。

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

这篇关于正则表达式中的if语句匹配空格的字符串(用引号?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆