如何在Bash中使用正则表达式匹配空格?

时间:2015-01-31 20:27:25

标签: regex bash

我希望下面的代码能够回应"是",但事实并非如此。出于某种原因,它不符合单引号。为什么呢?

str="{templateUrl: '}"
regexp="templateUrl:[\s]*'"

if [[ $str =~ $regexp ]]; then
  echo "yes"
else
  echo "no"
fi

3 个答案:

答案 0 :(得分:52)

替换:

regexp="templateUrl:[\s]*'"

使用:

regexp="templateUrl:[[:space:]]*'"

根据man bash=~运算符支持man 3 regex中定义的“扩展正则表达式”。 man 3 regex表示它支持POSIX标准,并引用读者man 7 regex。 POSIX标准支持[:space:]作为空格的字符类。

GNU bash manual记录支持的字符类,如下所示:

  

在'['和']'中,可以使用。指定字符类   语法[: class :],其中 class 是以下定义的类之一   在POSIX标准中:

     

alnum alpha ascii blank cntrl digit graph lower print
  punct space upper word xdigit

我在GNU \s文档中发现bash的唯一提及是在提示中使用不相关的内容,例如PS1,而不是正则表达式。

*

的含义

[[:space:]]将匹配一个空白字符。 [[:space:]]*将匹配零个或多个空白字符。

spaceblank

之间的差异

POSIX regular expressions提供两类空白:[[:space:]][[:blank:]]

  • [[:blank:]]表示空格和制表符。这使其类似于:[ \t]

  • [[:space:]]除了空格和标签外,还包括换行符,换行符,换页符和垂直标签。这使其类似于:[ \t\n\r\f\v]

使用字符类的一个关键优势是它们对于unicode字体是安全的。

答案 1 :(得分:3)

摆脱正则表达式中的方括号:

regexp="templateUrl:\s*'"

如果使用方括号,\s内部会被解释为与\s字符匹配,但您的意图显然与白色空格字符类匹配其中\s是简写(因此不需要方括号)。

$ uname -a
Linux noname 3.13.0-24-generic #47-Ubuntu SMP Fri May 2 23:30:00 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux
$ bash --version
GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it. 
There is NO WARRANTY, to the extent permitted by law.
$ cat test.sh
str="{templateUrl: '}" 
regexp="templateUrl:\s*'"

if [[ $str =~ $regexp ]]; then
  echo "yes"
else
  echo "no"
$ bash test.sh
yes 

答案 2 :(得分:3)

这应该有效:

#!/bin/bash
str="{templateUrl: '}"
regexp="templateUrl:[[:space:]]*'"

if [[ $str =~ $regexp ]]; then
  echo "yes"
else
  echo "no"
fi

如果您想匹配零个或多个空格,*需要在[[:space:]]之后添加。