From: Robert Dober Date: 2006-07-27T06:03:04+09:00 Subject: Re: gsub ------=_Part_32169_32286249.1153947781493 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline Sorry about yet another post, but I think this is noteworthy... Well that is nice ;) > actually that would be something like > > s.sub( %r{#{Regexp.escape(r)}(?!.*#{Regexp.escape(r)})},"") > > but I am afraid that this is much more expensive than the > reverse.sub.reverse trick and much less readable > > Robert > Variable length lookahead assertions are a killer, just look at this, I have replaced the last < in this page with *** that is a string of length 2369, look at the benchmark please: robert@roma:~/log/ruby/theory/regex$ cat test2.rb && ./test2.rb #!/usr/bin/env ruby # # require 'benchmark' string = nil File.open("gsub.html"){ | file | string = file.read } s1=s2=nil r1 = Regexp.new( "<" ) r2 = Regexp.new( "<(?!.*<)", Regexp::MULTILINE ) n = 50000 Benchmark.bm do |x| x.report("reverse.sub.reverse") { n.times do s1 = string.reverse.sub(r1,"***").reverse end } x.report("lookahead") { n.times do s2 = string.sub(r2,"***") end } end user system total real reverse.sub.reverse 1.470000 0.010000 1.480000 ( 1.483691) lookahead 48.100000 0.060000 48.160000 ( 52.608063) As far as I know fixed with lookahead is about ok, though. Cheers Robert ------=_Part_32169_32286249.1153947781493--