In article <slrnbhr0jv.d34.usenet / home.andreas-s.net>,
Andreas Schwarz  <usenet / andreas-s.net> wrote:
>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.

You can use Regexp.escape rather than write one yourself.

[mike@ratdog mike]$ ri Regexp::escape
This is a test 'ri'. Please report errors and omissions
on http://www.rubygarden.org/ruby?RIOnePointEight
 
 --------------------------------------------------------- Regexp::escape
      Regexp.escape( aString ) -> aNewString
 ------------------------------------------------------------------------
      Escapes any characters that would have special meaning in a regular
      expression. For any string, Regexp.escape(str)=~str will
      be true.
              Regexp.escape('\\*?{}.')   #=> \\\\\*\?\{\}\.

e.g.

[mike@ratdog mike]$ irb --simple-prompt
>> s = 'Oh $*.?!'
=> "Oh $*.?!"
>> s.gsub(/#{Regexp.escape('$*.?')}/, 'dear')
=> "Oh dear!"

Hope this helps,

Mike

-- 
mike / stok.co.uk                    |           The "`Stok' disclaimers" apply.
http://www.stok.co.uk/~mike/       | GPG PGP Key      1024D/059913DA 
mike / exegenix.com                  | Fingerprint      0570 71CD 6790 7C28 3D60
http://www.exegenix.com/           |                  75D2 9EC4 C1C0 0599 13DA