Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stumped by a simple regex

Tags:

regex

ruby

I am trying to see if the string s contains any of the symbols in a regex. The regex below works fine on rubular.

s = "asd#d"
s =~ /[~!@#$%^&*()]+/

But in Ruby 1.9.2, it gives this error message:

syntax error, unexpected ']', expecting tCOLON2 or '[' or '.'
s = "asd#d"; s =~ /[~!@#$%^&*()]/

What is wrong?

like image 637
Zabba Avatar asked Feb 29 '12 03:02

Zabba


2 Answers

This is actually a special case of string interpolation with global and instance variables that most seem not to know about. Since string interpolation also occurs within regex in Ruby, I'll illustrate below with strings (since they provide for an easier example):

@foo = "instancefoo"
$foo = "globalfoo"
"#@foo" # => "instancefoo"
"#$foo" # => "globalfoo"

Thus you need to escape the # to prevent it from being interpolated:

/[~!@\#$%^&*()]+/

The only way that I know of to create a non-interpolated regex in Ruby is from a string (note single quotes):

Regexp.new('[~!@#$%^&*()]+')
like image 103
Andrew Marshall Avatar answered Nov 11 '22 22:11

Andrew Marshall


I was able to replicate this behavior in 1.9.3p0. Apparently there is a problem with the '#$' combination. If you escape either it works. If you reverse them it works:

s =~ /[~!@$#%^&*()]+/

Edit: in Ruby 1.9 #$ invokes variable interpolation, even when followed by a % which is not a valid variable name.

like image 21
Mark Thomas Avatar answered Nov 11 '22 20:11

Mark Thomas