Zabba
Zabba

Reputation: 65467

Stumped by a simple regex

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?

Upvotes: 7

Views: 219

Answers (3)

Andrew Marshall
Andrew Marshall

Reputation: 96914

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('[~!@#$%^&*()]+')

Upvotes: 12

Mark Thomas
Mark Thomas

Reputation: 37507

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.

Upvotes: 1

TheDelChop
TheDelChop

Reputation: 7998

I disagree, you need to escape the $, its the end of string character.

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

That is correct.

Upvotes: -3

Related Questions