Suppose input = "Hello" and pattern is "World" I want to determinine that thr pattern does not occur in input. Sinc开发者_开发知识库e pattern does not occur in input Regex.IsMatch should return true.
How can I write the pattern in C#
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.
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);
精彩评论