Search code examples
c#.netregexregex-lookarounds

Variable-length lookbehind for backslashes


What seemed to be a simple task ended up to not work as expected...

I'm trying to match \$\w+\b, unless it's preceded by an uneven number of backslashes.

Examples (only $result should be in the match):

This $result should be matched

This \$result should not be matched

This \\$result should be matched

This \\\$result should not be matched

etc...

The following pattern works:

(?<!\\)(\\\\)*\$\w+\b

However, even repeats of backslashes are included in the match, which is unwanted, so I'm trying to achieve this purely with a variable-length lookbehind, but nothing I tried so far seems to work.

Any regex virtuoso here can lend a hand?


Solution

  • You may use the following pattern:

    (?<!(?:^|[^\\])\\(?:\\\\)*)\$\w+\b
    

    Demo.

    Breakdown of the Lookbehind; i.e., not preceded by:

    • (?:^|[^\\]) - Beginning of string/line or any character other than backslash.
    • \\ - Then, one backslash character.
    • (?:\\\\)* Then, any even number of backslash characters (including zero).