tags:

views:

659

answers:

3

I have the following regex:

s/\\/\\\\/g

This does a nice job of replacing all "\" characters with "\\". However, I want to guard against matching backslashes that are adjacent to other backslashes. If I do this:

s/[^\\]\\[^\\]/\\\\/g

it only catches non-adjacent backslashes. But now there's the obvious problem that the matches include the two neighboring charaters that shouldn't be replaced. How can I overcome this?

A: 

If you know what escaped characters you want to match you can always just include all those cases (\n,\r,\t,\"....)

Gegtik
+3  A: 

How about a negative lookahead to specify "replace this slash unless it is followed by another slash"?

George Mauer
Thanks, as a regex beginner I just needed to hear the term "lookahead". I have what I need now.
Odrade
+1 on the lookahead
DevelopingChris
A: 

s/([^\\])\\([^\\])/$1\\\\$2/g

agsamek
you want to leave the $1 and $2 out ...
tanascius
Does this miss a beginning of line backslash? End of line (not that that would likely be a concern)?
John Pirie
Yes. It also misses backslashes separated by a single char. But it matches the question :)
agsamek
he wants to make 'blo\blo' to 'blo\\blo', but not 'blo\\blo' to 'blo\\\\blo' ...
tanascius