special characters within [] in a regexp

M

Martin DeMello

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
 
C

Carlos

Martin said:
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 $%.

--
 
M

Martin DeMello

Martin said:
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 :) Thanks.

martin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top