What is the proper regular expression for an unescaped backslash before a character?

Updated: My new and improved Perl regex, supporting more than 3 backslashes:

/(?<!\\)    # Not preceded by a single backslash
  (?>\\\\)* # an even number of backslashes
  \\q       # Followed by a \q
  /x;

or if your regex library doesn't support extended syntax.

/(?<!\\)(?>\\\\)*\\q/

Output of my test program:

q does not match
\q does match
\\q does not match
\\\q does match
\\\\q does not match
\\\\\q does match

Older version

/(?:(?<!\\)|(?<=\\\\))\\q/

Leon Timmermans got exactly what I was looking for. I would add one small improvement for those who come here later:

/(?<!\\)(?:\\\\)*\\q/

The additional ?: at the beginning of the (\\\\) group makes it not saved into any match-data. I can't imagine a scenario where I'd want the text of that saved.

Tags:

Regex