为什么会出现这个错误?
Regexp.new("[#$]")
# => SyntaxError: (irb):1: syntax error, unexpected $undefined
# => Regexp.new("[#$]")
# ^
# (irb):1: unterminated string meets end of file
# from ~/.rvm/rubies/ruby-1.9.3-p194/bin/irb:1:in `<main>'
这应该从字面上描述由单个 $
或 #
组成的字符串子集。还有,AFAIU Ruby's Regexp engine , #
和 $
don't need to be escaped在字符类中,即使它们通常是元字符。
我会从错误消息中猜测,当 Ruby 在双引号内命中 #
时,它正试图插入 $
,但是...为什么?订购很重要。 $
和 #
字符有多个重载行为,所以我不知道是什么触发了这个。
附言,仅供引用:
/[#$]/
# => SyntaxError: (irb):1: syntax error, unexpected $undefined
/[$#]/
# => /[$#]/
Regexp.new '[$#]'
# => /[$#]/
Regexp.new '[#$]'
# => /[#$]/
Regexp.new "[#$]"
# => SyntaxError: (irb):1: syntax error, unexpected $undefined
最佳答案
问题不是$
,而是#
,因为#...
通常用于双引号字符串中的变量扩展。喜欢 "#{x}"
。
但问题是您也可以直接使用 #$global
扩展全局变量,这就解释了您的问题:
$global = "hello"
"#$global"
=> "hello"
所以解决方案是转义either #
或 $
,因为这会破坏字符串插值状态机器将构造解释为插值:
puts "\#$global"
=> #$global
puts "#\$global"
=> #$global
编辑
只是为了说清楚 :) 问题不在于 Regexp
,而是您在键入 时试图扩展名为
:$]
的全局变量>“#$]”
puts "#$]"
SyntaxError: (irb):22: syntax error, unexpected $undefined
要修复它你需要转义一些东西:
puts "\#$]"
=> #$]
关于Ruby 正则表达式插值/字符类/全局变量语法冲突?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10725139/