William James
9/10/2007 4:59:00 PM
On Sep 10, 7:55 am, "Robert Klemme" <shortcut...@googlemail.com>
wrote:
> 2007/9/10, Ronald Fischer <ronald.fisc...@venyon.com>:
>
> > I thought this would be a trivial task, but it seems to be more
> > difficult than expected:
>
> > I have a variable, data, containing some string. I would like to
> > preprend every
> > single apostrophe in this string by a backslash. Here is my solution:
>
> > data.gsub!(/'/,%q(\\'))
>
> > Strangely, this does not work. I tested it with data containing a string
> > consisting
> > of a single quote solely, and surrounded the code by "puts" like this:
>
> > data=%q(')
> > puts ":"+data+" replace quotes by "+%q(\\')
> > data.gsub!(/'/,%q(\\'))
> > puts "data length now #{data.length}"
>
> > This produced as output:
>
> > :' replace quotes by \'
> > data length now 0
>
> > From this I conclude that the gsub! had shortened the string to length
> > zero.
> > Any explanation for this? How do I solve my problem in a proper way?
>
> This comes up frequently. You need to be aware that there are several
> levels of interpretation involved and so you need multiple levels of
> escaping. This is sometimes obscured by the fact that '\1' works
> although it should read '\\1'. These levels are: 1. string escaping,
> 2. regexp replacement string escaping. All these variants do work:
>
> str.gsub /'/, '\\\\\\&'
> str.gsub /'/, '\\\\\''
> str.gsub /'/, "\\\\'"
str.gsub /(?=')/, "\\"