Search code examples
c#regexescapingquotes

c# - How to match specific character which is not inside quotes


I would like to match all the occurrences of / that are not included in quotes (i.e. ").

For e.g, this would be the result of the matches

HKEY/"SOFTWARE"/"test/123"/

HKEY/"SOFTWARE"/test

HKEY/SOFTWARE/"test/123"/

HKEY/SOFTWARE/test//test

HKEY/SOFTWARE/"test

HKEY/SOFTWARE/"test/

So far, I have tried using /((?=[^""]*(?:""[^""]*""[^""]*)*$)).

I've looked at other answers but they don't work (or are in different languages).


Solution

  • The logic of your current regex is to look ahead for balanced quotes. But if you have unclosed quotes, this will not work. However you can just switch the direction to look behind towards start.

    (?m)/(?<=^(?:[^"\n]*"[^"\n]*")*[^"\n]*)
    

    See this demo at Regex Storm (drop (?m) and \n if single lines are processed, add escapes).


    For just removing these slashes it would suffice to replace such as ("[^"\n]*(?:"|$))|/+ with $1. This does not work if you need to replace the matched character with something else though.
    Other in PCRE/PHP, a variant with verbs could be used to replace: "[^"\n]*(?:"|$)(*SKIP)(*F)|/