Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

regex - 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Replace:

regexp="templateUrl:[s]*'"

With:

regexp="templateUrl:[[: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.

The GNU bash manual documents the supported character classes as follows:

Within ‘[’ and ‘]’, character classes can be specified using the syntax [:class:], where class is one of the following classes defined in the POSIX standard:

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

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.

The Meaning of *

[[:space:]] will match exactly one white space character. [[:space:]]* will match zero or more white space characters.

The Difference Between space and blank

POSIX regular expressions offer two classes of whitespace: [[:space:]] and [[:blank:]]:

  • [[:blank:]] means space and tab. This makes it similar to: [ ].

  • [[:space:]], in addition to space and tab, includes newline, linefeed, formfeed, and vertical tab. This makes it similar to: [ fv].

A key advantage of using character classes is that they are safe for unicode fonts.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...