Unexpected abbreviated character classes work

Regular expression

/[\D\S]/ 

must match characters that are not numbers or no spaces

But when I check this expression in regexpal

He begins to match any character of this digit, a space

What am I doing wrong?

+4
source share
2 answers

\D = all characters except numbers, \S = all characters except spaces

[\D\S] = union (set theory) of the indicated groups of characters = all characters.

Why? Since \D contains \S and \S contains \D

If you want to match characters that are not periods or spaces, you can use [^\d\s] .

+6
source

Your regular expression is invalid. Putting a regular expression inside [] means that it must match one of the elements inside it. These two elements redefine each other, which ultimately corresponds to all. Theoretically, anything that is not a number will match any other char. available, and any spaces match any digit and any other char. also.

You can try using [^\d\s] , which says to negate the match of any digit or any space. Instead of catching everything in the original regular expression, it negates the match of both \d and \s . You can see how testing with him is here .

+1
source

Source: https://habr.com/ru/post/1481964/


All Articles