Reputation: 105037
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
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
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