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

regex

Solution

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/

Problem

Let's say I want to represent `\q` (or any other particular "backslash-escaped character"). That is, I want to match `\q` but not `\\q`, since the latter is a backslash-escaped backslash followed by a `q`. Yet `\\\q` would match, since it's a backslash-escaped backslash followed by a backslash-escaped `q`. (Well, it would match the `\q` at the end, not the `\\` at the beginning.) I know I need a negative lookbehind, but they always tie my head up in knots, especially since the backslashes themselves have to be escaped in the regexp.

Original source