Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Character classes and negation with Regex

Tags:

c#

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.

like image 459
devoured elysium Avatar asked Mar 05 '13 00:03

devoured elysium


People also ask

How do I use character class in regex?

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.

What are character classes in regex?

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.

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.

What does regex 0 * 1 * 0 * 1 * Mean?

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.


1 Answers

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);
}
like image 191
Ahmad Mageed Avatar answered Sep 22 '22 12:09

Ahmad Mageed