From: Robert Klemme Date: 2003-07-23T23:45:31+09:00 Subject: Re: String substitution without RegEx "Andreas Schwarz" schrieb im Newsbeitrag news:slrnbht3o8.2jq.usenet@home.andreas-s.net... > Robert Klemme wrote: > > > > "Andreas Schwarz" schrieb im Newsbeitrag > > news:slrnbhr0jv.d34.usenet@home.andreas-s.net... > >> I wanted to do a simple string substitution, and was surprised to see > >> that there isn't such a method in ruby. I can't use String::(g)sub, > >> because the substitution mustn't be influenced by special chars or > >> backreferences in the pattern and replacement strings. Of course I could > >> write functions to escape regex special chars in the pattern and > >> backreferences in the replacement string, but this is about the ugliest > >> solution I can think of. > > > > Where's the problem? > > > > irb(main):004:0> "foo.bar".gsub '.', "*" > > (irb):4: warning: string pattern instead of regexp; metacharacters no > > longer eff > > ective > > "foo*bar" > > irb(main):001:0> "foo.bar".gsub '.', "*" > => "*******" Ah, then it's a ruby version thingy. I used 1.7.3. Which one do you have? > > Or you use Regexp.escape as others already have pointed out: > > > > irb(main):017:0* "foo.bar".gsub( /#{Regexp.escape(".")}/, "*" ) > > "foo*bar" > > irb(main):007:0> "foo.bar".gsub( /#{Regexp.escape(".")}/, "\\1") > => "foobar" Why do you use \1 if you want to replace a fixed string? Or do you want to insert \1? Then you shoul've done "foo.bar".gsub( /#{Regexp.escape(".")}/, Regexp.escape("\\1") ) Cheers robert