Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net Regular expression - how to do an exact match exclusion on a full string?

Tags:

.net

regex

I need a .NET regular expression that matches anything other than the exact full string match specified. So basically:

^Index$

... is the only exclusion I care about. Strings can start with, finish with or contain "Index", but not match exactly.

The answer must be via the pattern itself, as I am passing an argument to a third-party library and do not have control over the process other than via the Regex pattern.

like image 892
Nathan Ridley Avatar asked Apr 12 '10 10:04

Nathan Ridley


2 Answers

This should do the trick:

^(?!Index$)
like image 52
Lucero Avatar answered Sep 28 '22 06:09

Lucero


If a regular expression is a must,

Match match = Regex.Match(input, @"^Index$");

if (!match.Success){
    // Do something
}

And with a horrible way

Match match = Regex.Match(input, @"^(.*(?<!Index)|(?!Index).*)$");

if (match.Success){
    // Do something
}

Note: the second one is not tested, and the regular expression engine needs to support full look ahead and look behind.

like image 32
YOU Avatar answered Sep 28 '22 05:09

YOU