tags:

views:

62

answers:

2

Suppose input = "Hello" and pattern is "World" I want to determinine that thr pattern does not occur in input. Since pattern does not occur in input Regex.IsMatch should return true.

How can I write the pattern in C#

+1  A: 

Normally you don't use regular expressions to check for whether a certain substring DOES NOT exist.

While it is possible in some (regex implementations) to use zero-width negative lookarounds (see this answer), it's not necessarily possible for every input. Negative lookahead/behind assertions are primarily used when you want to avoid exponential matching failure in a regular expression by asserting that certain subcases do not exist before/after/within your match. They're also (more commonly) used when searching for matches that must not be preceded or followed by some other pattern.

Instead, just check if the pattern exists in the input, and then return the negation of Regex.IsMatch:

var input = "Hello";
var regEx = new Regex("World");
return !regEx.IsMatch(input);
LBushkin
the thing is the pattern comes from a config file and I wanted to run the same matching either way
DotDot
+2  A: 

You can use a zero-width, negative lookahead assertion:

Regex.IsMatch("Hello", "(?!World)") // Returns true

But I'm only providing you with that information on the condition that you do not just do exactly and only that (when you can just negate IsMatch result), and instead want to have a negative assertion somewhere in a more sensible place.

Marc Bollinger