ruby正则表达式命名和组

ced*_*emo 1 ruby regex

我试图在正则表达式中使用命名组但它不起作用:

module Parser
  def fill(line, pattern)
    if /\s#{pattern}\:\s*(\w+)\s*\;/ =~ line
      puts Regexp.last_match[1]
      #self.send("#{pattern}=", value)
    end
    if /\s#{pattern}\:\s*(?<value>\w+)\s*\;/ =~ line
      puts value
      #self.send("#{pattern}=", value)
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

正如你所看到我首先测试我的正则表达式然后我尝试使用与命名组相同的正则表达式.

class Test
  attr_accessor :name, :type, :visible
  include Parser #add instance method (use extend if we need class method)
  def initialize(name)
    @name = name
    @type = "image"
    @visible = true
  end
end

t = Test.new("toto")
s='desciption{ name: "toto.test"; type: RECT; mouse_events: 0;'
puts t.type
t.fill(s, "type")
puts t.type
Run Code Online (Sandbox Code Playgroud)

当我执行它时,第一个正则表达式工作,但不是第二个与命名组.这是输出:

./ruby_mixin_test.rb
image
RECT
./ruby_mixin_test.rb:11:in `fill': undefined local variable or method `value' for 
#<Test:0x00000001a572c8> (NameError)
from ./ruby_mixin_test.rb:34:in `<main>'
Run Code Online (Sandbox Code Playgroud)

Aru*_*hit 6

如果=~与具有命名捕获的正则表达式文字一起使用,则捕获的字符串(或nil)将分配给由捕获名称命名的局部变量.

/(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/ =~ "  x = y  "
p lhs    #=> "x"
p rhs    #=> "y"
Run Code Online (Sandbox Code Playgroud)

但是 - regexp插值#{},也会禁用赋值.

rhs_pat = /(?<rhs>\w+)/
/(?<lhs>\w+)\s*=\s*#{rhs_pat}/ =~ "x = y"
lhs    # undefined local variable
Run Code Online (Sandbox Code Playgroud)

在您的情况下,从以下代码:

if /\s#{pattern}\:\s*(?<value>\w+)\s*\;/ =~ line
   puts value
   #self.send("#{pattern}=", value)
end
Run Code Online (Sandbox Code Playgroud)

看下面的行,你使用插值

/\s#{pattern}\:\s*(?<value>\w+)\s*\;/ =~ line
 ~~^
Run Code Online (Sandbox Code Playgroud)

因此,当您报告未定义的局部变量或方法"值"时,未发生局部变量赋值并且出现错误.