Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

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.

like image 428
James A. Rosen Avatar asked Sep 11 '08 13:09

James A. Rosen


1 Answers

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/
like image 131
Leon Timmermans Avatar answered Oct 03 '22 09:10

Leon Timmermans