From: Florian Gross Date: 2004-11-04T06:53:46+09:00 Subject: Re: escaping single quotes in a string with gsub James Edward Gray II wrote: >> I'm trying to take a string and escape a single quote if it is not >> already escaped. My first thought was to look at the string and if I >> see a quote without a backslash before it put the backslash there. >> Would look-behind be an option here out of the box? > > Surprisingly, I don't believe Ruby yet supports lookbehind. However it does support look-ahead which is enough in this case: "foo bar don't \\'".gsub(/((?!\\).(?:\\{2})*)'/, "\\1\\\\'") # result: foo bar don\'t \' And since the escape string is only a single character: "foo bar don't \\'".gsub(/([^\\](?:\\{2})*)'/, "\\1\\\\'") # result: foo bar don\'t \' (Note that this is basically your Regexp, but with some of the filtering logic moved from the block to the Regexp itself. The replacement string looks disgusting. I think your solution is way clearer.) Here is a sample with a multiple-width escape string: "foo bar don't ESC'".gsub(/((?!ESC).{3}(?:(?:ESC){2})*)'/, "\\1ESC'") # result: foo bar donESC't ESC'