tags:

views:

68

answers:

4

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. My brain doesn't seem to be working today and I'm failing to work this one out.

EDIT

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.

+3  A: 

If Regex is Must,

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

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

And with horrible way

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

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

Note: second one is not tested, and regex engine need to support full look ahead and look behind

S.Mark
The second one works, Thanks!
Nathan Ridley
There is a simpler and faster way than the second, see my answer.
Lucero
Yeah, Absolutely!
S.Mark
A: 

What about if (!r.Match("^Index$").Success) ...?

Marcelo Cantos
No, it has to be in the regular expression syntax. The only control I have over what I'm doing here is via the pattern itself.
Nathan Ridley
A: 

you can check !regex.Match.Success

Andrey
+3  A: 

That should do the trick:

^(?!Index$)
Lucero
Yep, this works better. It's so obvious now that I think about it!
Nathan Ridley
Fantastic ! :-) -
S.Mark
Thanks Nathan and S.Mark!
Lucero