用正则表达式匹配空字符串 [英] Matching an empty string with regex
问题描述
我在 stackoverflow 上看到过一些帖子说正则表达式 ^$
将匹配一个空字符串......所以这让我想......为什么不是这样的:^\s+$
- 这也不行吗?我知道打字更多,但在我看来,它也更有意义.我以前没有使用过很多正则表达式,但随着时间的推移,我对它们的需求似乎越来越大 - 所以我正在接受提示并尝试学习.
^\s+$
- 这也不行吗?
不是用于匹配空字符串.一般来说,X+
表示X
一次或多次.所以,\s+
不能匹配空字符串——它至少需要一个 \s
才能匹配.
现在,X*
的意思是 X
0 次或多次,所以 ^\s*$
确实会匹配一个空字符串.
^\s+$
^\s*$
I've seen posts here on stackoverflow that say that the regex ^$
will match an empty string... So it made me think... why not something like this: ^\s+$
- does that not also work? I know it's more typing, but it in my mind, it also makes more sense. I've not used a whole lot of regex before, but it seems like my need for them is becoming greater as the days go by - so I'm taking the hint and attempting to learn.
^\s+$
- does that not also work?
Not for matching an empty string. In general, X+
means X
one or more times. So, \s+
cannot match the empty string - it requires at least one \s
in order to match.
^ \s + $ | | | | start of string ---------------------+ | | | whitespace character ------------------+ | | one or more of what precedes -------------+ | end of string ------------------------------+
Now, X*
means X
0 or more times, so ^\s*$
would indeed match an empty string.
^\s+$
^\s*$
这篇关于用正则表达式匹配空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!