# Special characters within \[\] in a regexp

**URL:** <https://www.ruby-forum.com/t/special-characters-within-in-a-regexp/64959>\
**Category:** Ruby\
**Created:** [August 15, 2006, 2:20pm UTC](https://www.ruby-forum.com/t/special-characters-within-in-a-regexp/64959 "2006-08-15T14:20:58Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Martin\_DeMello](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/f17d59/32.png) [@Martin\_DeMello](https://www.ruby-forum.com/u/Martin_DeMello)\
**Post date:** [August 15, 2006, 2:20pm UTC](https://www.ruby-forum.com/t/special-characters-within-in-a-regexp/64959/1 "2006-08-15T14:20:58Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![Martin\_DeMello](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/f17d59/32.png) [@Martin\_DeMello](https://www.ruby-forum.com/u/Martin_DeMello)\
**Post date:** [August 15, 2006, 2:21pm UTC](https://www.ruby-forum.com/t/special-characters-within-in-a-regexp/64959/2 "2006-08-15T14:21:05Z")

</div>

Martin DeMello wrote:

> (irb):2: parse error, unexpected $undefined.  
> Hi. You don’t need braces to interpolate global variables. “#$%” tries  
> to interpolate special variable $%.

---

<div class="post-metadata">

**Author:** ![Martin\_DeMello](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/f17d59/32.png) [@Martin\_DeMello](https://www.ruby-forum.com/u/Martin_DeMello)\
**Post date:** [August 15, 2006, 5:23pm UTC](https://www.ruby-forum.com/t/special-characters-within-in-a-regexp/64959/3 "2006-08-15T17:23:52Z")

</div>

On 8/15/06, Carlos [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> > ```
> > ^
> > 
> > ```
> > 
> > (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
