From: Robert Klemme Date: 2006-11-25T04:51:49+09:00 Subject: Re: double-slashes in input causing trouble Some more remarks: On 23.11.2006 17:53, Hugh Sasse wrote: > On Fri, 24 Nov 2006, Jeremy Wells wrote: > > [...] >> The problem is that if the section contains "\\" which mine does in places, >> ruby replaces these with a single "\" without my asking it to. >> >> Here is the basics of the program: >> body = "" Initializing body with an empty string is superfluous - nil is more efficient, but: >> File.open(input, 'r') do |file| >> body = file.read >> end You could as well replace those lines with body = File.read input >> if body =~ /^section\sheader(.*)section\sfooter/mi Dangerous to use .* which is greedy and will break if there are more sections in one file! >> original_section = $1 >> new_section = bit_at_top + original_section >> new_body = body.sub(original_section, new_section) > new_body = body.sub(Regexp.new(Regexp.quote(original_section)), > new_section) Now you do a replacement with sub which might replace some completely different piece of text (i.e. especially if the text of original_section appears outside a section or otherwise in multiple places. >> File.open(input,'w') do |file| >> file.write new_body >> end >> end > > # Hugh > So, combining these you get: body = File.read input if body.gsub!( %r{^(section\sheader)(.*?)(?=section\sfooter)}mi, '\\1your_head\\2') File.open(input, "w") {|io| io.write body} end Kind regards robert