On 6/11/07, Li Chen <chen_li3 / yahoo.com> wrote:
> 1) what is the best scenario to use Regexp.escape?
>
> 2) I modify my codes and I get the expected results. But the odd is that
> I have to use 3 backslashes before the 2nd 2. How to explain this.
>
> Thanks,
>
> Li
>
>
> DATA.each_line do |line|
>
>           if line=~/1\.000000\\\$P1G\\1\.000000/
>                line.gsub!(/1\.000000\\\$P1G\\1\.000000/,
> '2.000000\\\$P1G\\\2.000000')
>                puts line
>           end
>   end

How about this:

# In single quoted strings you only escape \ and '
# You can interpolate into a pattern literal.
pat = /#{Regexp.escape('1.000000\$P1G\1.000000')}/
# No need for Regexp.escape here since the second parameter to gsub!
# is a string, not a pattern.
sub = '2.000000\\$P1G\\2.000000')

And then either:

if line =~ pat
    line.gsub!(pat,sub)
    puts line
end

or just

puts line if line.gsub!(pat,sub)

since gsub! returns nil if no substitution was performed and the
string if it was.

-- 
Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/