From: Ken Bloom Date: 2007-06-12T00:10:19+09:00 Subject: Re: why gsub! doesn't work in my script On Mon, 11 Jun 2007 22:34:16 +0900, Li Chen wrote: > Hi all, > > I want to search one pattern in a file line by line and replace it with > new pattern one. But it doesn't work. I cannot change the old pattern > into the new one using gsub! Is there any problem with my script? > > Thanks, > > Li > > > > > ################Ruby script############## > > #create a regular expression and its replacement > > r1_obj=Regexp.escape('1.000000\$P1G\1.000000') #pattern > r2_obj=Regexp.escape('2.000000\$P1G\2.000000') #replacement > > > DATA.each_line do |line| > if line.match(r1_obj) > line.gsub!(r1_obj, r2_obj) # > puts line > end > end Regexp.escape takes a string as a parameter, and returns a string as its return value. When you use that string in your Regexp.escape call, you convert it into something that no longer matches the text in your file, and when you use the returned string in the gsub call, it tries to match it literally. irb(main):003:0> "...".gsub(Regexp.escape("."),"x") => "..." irb(main):004:0> "...".gsub(".","x") => "xxx" irb(main):005:0> "...".gsub(Regexp.new(Regexp.escape(".")),"x") => "xxx" -- Ken Bloom. PhD candidate. Linguistic Cognition Laboratory. Department of Computer Science. Illinois Institute of Technology. http://www.iit.edu/~kbloom1/