From: Robert Dober Date: 2006-07-27T15:37:04+09:00 Subject: Re: gsub ------=_Part_36977_1552507.1153982217601 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline On 7/26/06, Robert Dober wrote: > > Sorry about yet another post, but I think this is noteworthy... and yet another 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 ) that is stupid use non greedy 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) better but not god enough generous lookahead 14.900000 0.010000 14.910000 ( 15.481074) As far as I know fixed with lookahead is about ok, though. > Cheers > Robert > ------=_Part_36977_1552507.1153982217601--