Meryovi
Meryovi

Reputation: 6231

Exclude match in Regular Expression

Is it possible to ignore a specific match in a regular expression?

For example:

I have the following regular expression:

^[0-9]{2}$

But I don't want to match a specific string, let's say "12".

I think I'm looking for something like an and operator for regular expressions, but haven't been able to find anything like this in .NET / C#.

I would prefer to do this in the regular expression itself. Any advice or suggestion?

Upvotes: 1

Views: 3235

Answers (3)

Joe
Joe

Reputation: 15812

You're better off doing something like:

if (Regex.IsMatch(MyString, @"^[0-9]{2}$") && MyString != "12")
{
    // Do something
}

Regex are very powerful, but it's important to know when to NOT use them :)

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727137

You can use this ugly regexp:

^([02-9][0-9] | [1][013-9])$

Translated to plain English, it means "a two-digit string that does not start in 1, or a two-digit string that starts in 1 but does not have 2 as its second digit".

Upvotes: 1

Wrikken
Wrikken

Reputation: 70540

^[0-9]{2}(?<!12)$

Or the reverse:

^(?!12)[0-9]{2}$

Note that in this specific case, negating 1 specific match was easy. Sometimes it isn't, an sometimes it's (nigh) impossible, depends on the regex.

Upvotes: 4

Related Questions