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
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.
Now You Have Two Problems.
Just write a simple parser. If the regex ties your head up in knots now, just wait a month.
The best solution to this is to do your own string parsing as Regular Expressions don't really support what you are trying to do. (rep @Frank Krueger if you go this way, I'm just repeating his advice)
I did however take a shot at a exclusionary regex. This will match all strings that do not fit your criteria of a "\" followed by a character.
(?:[\\][\\])(?!(([\\](?![\\])[a-zA-Z])))
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/