Search code examples
regexnegative-lookbehind

Regex Negative Lookbehind with spases on c#


i can't understand regex Negative Lookbehind..

I need not to catch '(this)' if there was a 'not' word some spaces before. For example:

  1. ... (this) - catch
  2. ... not(this) - not catch
  3. ... not (this) - not catch too, but it do

Please tell me where i am wrong, i can't make it work. My template :

(?<!\bnot\b)\s*(\(.*?this.*?\))

And (?<!...) can't understand something like (?<!\bnot\b\s*)

https://regex101.com/r/mK1yQ1/1


Solution

  • Well, you are using a wrong online regex tester, you need one supporting .NET regex syntax. Regex101.com does not support .NET regex syntax.

    You may actually use

    (?<!\bnot\b\s*)\(this\)
    

    See this regex demo

    Pattern explanation:

    • (?<!\bnot\b\s*) - check and fail the match if there is a
      • \b - leading word boundary
      • not - not literal substring
      • \b - trailing word boundary
      • \s* - zero or more whitespaces
    • \( - a literal ( symbol
    • this - a literal string this
    • \) - a literal ) symbol.

    Note that this pattern does not match this in rtjtj bbg (this,and that). To make it match that this, you may add a ? (one or zero) quantifier after the last \) -> (?<!\bnot\b\s*)\(this\)?. You may further adjust the pattern.