有人可以解释 [^\d\s]
之间的区别吗?和 [\D\S]
?
来自 http://www.regular-expressions.info/shorthand.html 的描述不是很清楚:
Be careful when using the negated shorthands inside square brackets.
[\D\S]
is not the same as[^\d\s]
. The latter matches any character that is neither a digit nor whitespace. It matchesx
, but not8
. The former, however, matches any character that is either not a digit, or is not whitespace. Because all digits are not whitespace, and all whitespace characters are not digits,[\D\S]
matches any character; digit, whitespace, or otherwise.
他们对我来说似乎是一样的。或者我错过了什么?
最佳答案
[^\d\s]
将匹配不是数字或空格的单个字符。
[\D\S]
将匹配一个非数字或非空格的单个字符。
由于每个字符都不是数字或不是空格,因此第二个正则表达式将匹配任何字符。
相当于:
if (!(isdigit(c) || isspace(c))) ...
和
if (!isdigit(c) || !isspace(c)) ...
请注意,以下等价于第一个(根据德摩根定律):
if (!isdigit(c) && !isspace(c)) ...
关于regex - 正则表达式 [^\d\s] 和 [\D\S] 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23971008/