如何在Bash中使用正则表达式匹配空格? [英] How can I match spaces with a regexp in Bash?
问题描述
我希望下面的代码回显是",但事实并非如此.由于某种原因,它与单引号不匹配.为什么?
I expect the code below to echo "yes", but it does not. For some reason it won't match the single quote. Why?
str="{templateUrl: '}"
regexp="templateUrl:[\s]*'"
if [[ $str =~ $regexp ]]; then
echo "yes"
else
echo "no"
fi
推荐答案
替换:
regexp="templateUrl:[\s]*'"
使用:
regexp="templateUrl:[[:space:]]*'"
根据man bash
,=~
运算符支持man 3 regex
中定义的扩展正则表达式". man 3 regex
说它支持POSIX标准,并向读者推荐man 7 regex
. POSIX标准支持[:space:]
作为空白的字符类.
According to man bash
, the =~
operator supports "extended regular expressions" as defined in man 3 regex
. man 3 regex
says it supports the POSIX standard and refers the reader to man 7 regex
. The POSIX standard supports [:space:]
as the character class for whitespace.
GNU bash
手册将受支持的字符类记录为如下:
The GNU bash
manual documents the supported character classes as follows:
在"["和]"中,可以使用 语法[: class :],其中 class 是以下定义的类之一 在POSIX标准中:
Within ‘[’ and ‘]’, character classes can be specified using the syntax [:class:], where class is one of the following classes defined in the POSIX standard:
数字alpha ASCII空白cntrl数字图下部打印
点空间上位词xdigit
alnum alpha ascii blank cntrl digit graph lower print
punct space upper word xdigit
我在GNU bash
文档中唯一提到的\s
是在提示(例如PS1
)中而不是在正则表达式中无关地使用的.
The only mention of \s
that I found in the GNU bash
documentation was for an unrelated use in prompts, such as PS1
, not in regular expressions.
[[:space:]]
将匹配一个完全相同的空格字符. [[:space:]]*
将匹配零个或多个空格字符.
[[:space:]]
will match exactly one white space character. [[:space:]]*
will match zero or more white space characters.
POSIX正则表达式提供了两类空白:[[:space:]]
和[[:blank:]]
:
POSIX regular expressions offer two classes of whitespace: [[:space:]]
and [[:blank:]]
:
-
[[:blank:]]
表示空格和制表符.这使其类似于:[ \t]
.
[[:blank:]]
means space and tab. This makes it similar to:[ \t]
.
[[:space:]]
,除了空格和制表符之外,还包括换行符,换行符,换页符和垂直制表符.这使其类似于:[ \t\n\r\f\v]
.
[[:space:]]
, in addition to space and tab, includes newline, linefeed, formfeed, and vertical tab. This makes it similar to: [ \t\n\r\f\v]
.
使用字符类的主要优点是它们对于Unicode字体是安全的.
A key advantage of using character classes is that they are safe for unicode fonts.
这篇关于如何在Bash中使用正则表达式匹配空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!