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?
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('[~!@#$%^&*()]+')
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With