What is the difference between the regular expressions [^\d\s] and [\D\S]

regex

Solution

[^\d\s]

will match a single character that is NOT a digit or whitespace.

[\D\S]

will match a single character that IS a non-digit or non-whitespace.

Since every character is either not a digit or not whitespace, the second regex will match any character.

It's equivalent to the difference between:

if (!(isdigit(c) || isspace(c))) ...

and

if (!isdigit(c) || !isspace(c)) ...

Note that the following would be equivalent to the first one (by deMorgan's law):

if (!isdigit(c) && !isspace(c)) ...

Problem

Can somebody explain the difference between `[^\d\s]` and `[\D\S]`? The description from http://www.regular-expressions.info/shorthand.html is not really clear: 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. They seem to be same for me. Or do I miss something?

Original source