Daniel Wolf Daniel Wolf - 1 year ago 81
Ruby Question

Syntax error with $ anchor in regular expression

The following Ruby script results in a syntax error:

test = 'Hello world#'
test.sub!(/#$/, '!')
p test

I'd expect the output to be
"Hello world!"
. From my understanding, the regex should match any hash character at the end of a line. Then
should replace it with an exclamation point.

Instead, I'm getting the following error message:

tmp.rb:2: unterminated regexp meets end of file
tmp.rb:2: syntax error, unexpected end-of-input, expecting ')'
p test

It seems that the regex still continues after the second slash. If I change the regex to
(without the trailing
), it works as expected.

Answer Source

In Ruby # is used for interpolation and to add comments to the regexp.

Just escape the # to \#:

test = 'Hello world#'
test.sub!(/\#$/, '!')
#=> "Hello world!"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download