我期望以下代码输出"yes",但它没有。由于某些原因它无法匹配单引号。为什么呢?
str="{templateUrl: '}"
regexp="templateUrl:[\s]*'"
if [[ $str =~ $regexp ]]; then
echo "yes"
else
echo "no"
fi
替换:
regexp="templateUrl:[\s]*'"
使用:
regexp="templateUrl:[[:space:]]*'"
man bash
,=~
运算符支持 "extended regular expressions",并在 man 3 regex
中定义。 man 3 regex
表示它支持 POSIX 标准,并引用读者到 man 7 regex
。POSIX 标准支持使用 [:space:]
作为空格的字符类。
GNU bash
手册 记录了支持的字符类如下:
我在 GNU在 ' [ ' 和 ' ] ' 中,可以使用语法 [:class:] 指定字符类,其中 class 是 POSIX 标准中定义的以下类之一:
alnum alpha ascii blank cntrl digit graph lower print
punct space upper word xdigit
bash
文档中找到的唯一提到 \s
的地方是与提示符(例如 PS1
)中的无关用途,而不是正则表达式中。
*
的含义[[:space:]]
将匹配 一个 空格字符。 [[:space:]]*
将匹配 零个或多个 空格字符。
space
和 blank
的区别[[:space:]]
和 [[:blank:]]
:
[[:blank:]]
表示空格和制表符。 这使它类似于: [ \t]
。
[[:space:]]
除了空格和制表符外,还包括换行符、回车符、换页符和垂直制表符。 这使它类似于: [ \t\n\r\f\v]
。
去掉正则表达式中的方括号:
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
regexp="templateUrl:\s*'"
对我仍然输出 "no" 。 - user810606
#!/bin/bash
str="{templateUrl: '}"
regexp="templateUrl:[[:space:]]*'"
if [[ $str =~ $regexp ]]; then
echo "yes"
else
echo "no"
fi
[[:space:]]
后面添加*
。*
。 - user810606GNU bash,版本4.2.25
中不需要它。 - heemayl*
。如果您想匹配 恰好 一个空格,则不需要使用它。 - John1024#!/bin/bash
str="{templateUrl: '}"
if [[ $str =~ templateUrl:" "*"'" ]]; then
echo "yes"
else
echo "no"
fi
感谢 Malak Younes。
[:space:]
意味着所有空格,包括回车和换行;而[:blank:]
意味着“水平”的空格(空格和制表符)-- http://www.regular-expressions.info/posixbrackets.html - glenn jackmanregexp="templateUrl:\ *'"
- Christoph Thiederegexp="templateUrl: *'"
也可以工作。当然,在任何情况下,这都限制了正则表达式匹配实际的ASCII空格。其他可能被[[:blank:]]
或[[:space:]]
识别的空白字符不会被匹配。 - John1024