正则表达式中 $ anchor 的语法错误

Syntax error with $ anchor in regular expression

以下 Ruby 脚本导致语法错误:

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

我希望输出为 "Hello world!"。据我了解,正则表达式应该匹配行尾的任何散列字符。那么sub!应该用感叹号代替。

相反,我收到以下错误消息:

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

似乎正则表达式在第二个斜线后仍然继续。如果我将正则表达式更改为 /#/(没有尾随 $),它会按预期工作。

在 Ruby 中 # 用于插值并向正则表达式添加注释。

只需将 # 转义为 \#:

test = 'Hello world#'
test.sub!(/\#$/, '!')
#=> "Hello world!"