Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么在Ruby中捕获命名组会导致;未定义的局部变量或方法;错误?_Ruby_Regex_Exception_Capture - Fatal编程技术网

为什么在Ruby中捕获命名组会导致;未定义的局部变量或方法;错误?

为什么在Ruby中捕获命名组会导致;未定义的局部变量或方法;错误?,ruby,regex,exception,capture,Ruby,Regex,Exception,Capture,我在Ruby 2.0的正则表达式中遇到命名捕获问题。我有一个字符串变量和一个插值正则表达式: str = "hello world" re = /\w+/ /(?<greeting>#{re})/ =~ str greeting 分配匹配的结果;这将作为散列进行访问,允许您查找命名的捕获组: > matches = "hello world".match(/(?<greeting>\w+)/) => #<MatchData "hello" greeti

我在Ruby 2.0的正则表达式中遇到命名捕获问题。我有一个字符串变量和一个插值正则表达式:

str = "hello world"
re = /\w+/
/(?<greeting>#{re})/ =~ str
greeting

分配匹配的结果;这将作为散列进行访问,允许您查找命名的捕获组:

> matches = "hello world".match(/(?<greeting>\w+)/)
=> #<MatchData "hello" greeting:"hello">
> matches[:greeting]
=> "hello"
命名捕获必须使用文本 您遇到了Ruby正则表达式库的一些限制。该方法对命名捕获的限制如下:

  • 如果regexp不是文本,则不会发生赋值
  • regexp插值,
    {}
    也会禁用赋值
  • 如果将regexp放置在右侧,则不会发生赋值

您需要决定是在正则表达式中使用命名捕获还是插值。您目前不能同时拥有这两个答案。

作为这两个答案的附录,以明确说明:

str = "hello world"
# => "hello world"
re = /\w+/
# => /\w+/
re2 = /(?<greeting>#{re})/
# => /(?<greeting>(?-mix:\w+))/
md = re2.match str
# => #<MatchData "hello" greeting:"hello">
md[:greeting]
# => "hello"
str=“你好,世界”
#=>“你好,世界”
re=/\w+/
#=>/\w+/
re2=/(?#{re})/
#=>/(?-mix:\w+)/
md=re2.match str
# => #
md[:问候语]
#=>“你好”

插值对于命名捕获很好,只需使用MatchData对象,最容易通过
match

返回,谢谢:),但我仍然无法解释这种奇怪行为的原因match没有创建新变量,它返回一个散列,其中键名是命名匹配项。因此,当你试图访问
问候语时,它并不存在。正如@ChrisHeald建议的那样,我尝试了以下方法:irb(main):016:0>matches=“hello world”。match(/(?#{re})/)=>#irb(main):017:0>匹配[:问候]=>“hello”和它works@giuseta完全不同的方法。另外,请注意,在使用时,您仍然没有分配给局部变量;您只是在数组中创建一个索引。在这两种情况下,问候语变量都未定义。
> "hello world".match(/(?<greeting>\w+)/) {|matches| matches[:greeting] }
=> "hello"
str = "hello world"
# => "hello world"
re = /\w+/
# => /\w+/
re2 = /(?<greeting>#{re})/
# => /(?<greeting>(?-mix:\w+))/
md = re2.match str
# => #<MatchData "hello" greeting:"hello">
md[:greeting]
# => "hello"