Character Classes and Negation with Regex

I was wondering if there is a way with Regex to accept characters associated with a given WHILE character set that negates a couple of other characters?

For example, consider the case where I want to accept all characters, numbers, and underscores ( \w), except for a letter eand a number 1. Is there a quick way to do this? Ideally, I would like something similar to ^[\w^e1]$, although I know that this particular one will not work.

+5
source share
2 answers

You can achieve this by subtracting the character class :

[base_group - [excluded_group]]

, ^[\w-[e1]]$ - , e 1.

string[] inputs = 
{
    "a", "b", "c", "_", "2", "3",
    " ", "1", "e"   // false cases
};
string pattern = @"^[\w-[e1]]$";
foreach (var input in inputs)
{
    Console.WriteLine("{0}: {1}", Regex.IsMatch(input, pattern), input);
}
+6

, , , , , e 1.

[a-df-zA-DF-Z02-9]

.

0

All Articles