devoured elysium
devoured elysium

Reputation: 105037

Character classes and negation with Regex

I was wondering if there's any way with Regex to accept the characters associated with a given character set WHILE negating a couple of other characters?

For instance, consider the case where I want to accept all the characters, digits and underscores (\w) except the letter e, and the digit 1. Is there a quick way to accomplish that? Ideally, I'd love something akin to ^[\w^e1]$, although I know this specific one won't work.

Upvotes: 5

Views: 1005

Answers (2)

Ahmad Mageed
Ahmad Mageed

Reputation: 96477

You can achieve this via character class subtraction:

[base_group - [excluded_group]]

Using this format, the pattern ^[\w-[e1]]$ can be used to match all alphanumeric characters excluding the letter e and number 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);
}

Upvotes: 6

Jason Larke
Jason Larke

Reputation: 5599

A more portable but less succinct way than Ahmad's solution would be to just define a character class that excludes e and 1.

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

Should work as expected.

Upvotes: 0

Related Questions