Special characters within [] in a regexp

What characters have to be escaped within a [] in a regular
expression? I was a bit taken aback by the following:

irb(main):001:0> a = '!#$%^&*((*)*_GHF$%#$*^%&;2~__)+|{}|{\\'
=> "!\#$%^&*((*)*_GHF$%\#$*^%&;2~__)+|{}|{\\"
irb(main):002:0> a.gsub(/[!@#$%^&*+={}|\\]/, '_')
SyntaxError: compile error
(irb):2: parse error, unexpected $undefined.
a.gsub(/[!@#$%^&*+={}|\\]/, '_')
             ^
(irb):2: parse error, unexpected $undefined.
a.gsub(/[!@#$%^&*+={}|\\]/, '_')
                       ^
(irb):2: parse error, unexpected ')', expecting $
        from (irb):2
irb(main):003:0> a.gsub(/[!@#$\%^&*+={}|\\]/, '_')
=> "_\#$____((_)__GHF$_\#$____;2~__)_______"
irb(main):004:0> a.gsub(/[!@#\$\%^&*+={}|\\]/, '_')
=> "_______((_)__GHF________;2~__)_______"

martin

Martin DeMello wrote:

What characters have to be escaped within a in a regular
expression? I was a bit taken aback by the following:

irb(main):001:0> a = '!#$%^&*((*)*_GHF$%#$*^%&;2~__)+|{}|{\\'
=> "!\#$%^&*((*)*_GHF$%\#$*^%&;2~__)+|{}|{\\"
irb(main):002:0> a.gsub(/[!@#$%^&*+={}|\\]/, '_')
SyntaxError: compile error
(irb):2: parse error, unexpected $undefined.
a.gsub(/[!@#$%^&*+={}|\\]/, '_')
            ^
(irb):2: parse error, unexpected $undefined.

Hi. You don't need braces to interpolate global variables. "#$%" tries to interpolate special variable $%.

···

--

Martin DeMello wrote:
> What characters have to be escaped within a in a regular
> expression? I was a bit taken aback by the following:
>
> irb(main):001:0> a = '!#$%^&*((*)*_GHF$%#$*^%&;2~__)+|{}|{\\'
> => "!\#$%^&*((*)*_GHF$%\#$*^%&;2~__)+|{}|{\\"
> irb(main):002:0> a.gsub(/[!@#$%^&*+={}|\\]/, '_')
> SyntaxError: compile error
> (irb):2: parse error, unexpected $undefined.
> a.gsub(/[!@#$%^&*+={}|\\]/, '_')
> ^
> (irb):2: parse error, unexpected $undefined.

Hi. You don't need braces to interpolate global variables. "#$%" tries
to interpolate special variable $%.

Oh! Okay, I get it now :slight_smile: Thanks.

martin

···

On 8/15/06, Carlos <angus@quovadis.com.ar> wrote:

--