regex - 正则表达式 [^\d\s] 和 [\D\S] 有什么区别

标签 regex

有人可以解释 [^\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 matches x, but not 8. 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/

相关文章:

sql - 如何仅在 VARCHAR2 列中允许字母 (Oracle SQL)

java - 使用java无需标记即可查找和替换

javascript - 正则表达式封装

regex - 将 grep 的匹配项存储在变量中

python - 用于匹配 URL 中电子邮件的正则表达式

python - 如何消除 ☎ unicode?

javascript - 转义 Javascript 字符串,未终止的字符类错误

c++ - 用于匹配 C++ 字符串常量的正则表达式

Java:验证文本字段输入是否仅包含字母字符

正则表达式匹配一个模式但不包括另一个模式