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.
With a “character class”, also called “character set”, you can tell the regex engine to match only one out of several characters. Simply place the characters you want to match between square brackets. If you want to match an a or an e, use [ae]. You could use this in gr[ae]y to match either gray or grey.
In the context of regular expressions, a character class is a set of characters enclosed within square brackets. It specifies the characters that will successfully match a single character from a given input string.
[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.
Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With