为什么在Ruby中捕获命名组会导致生成“未定义的局部变量或方法”?错误? [英] Why does capturing named groups in Ruby result in "undefined local variable or method" errors?

查看:76
本文介绍了为什么在Ruby中捕获命名组会导致生成“未定义的局部变量或方法”?错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am having trouble with named captures in regular expressions in Ruby 2.0. I have a string variable and an interpolated regular expression:

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

它引发以下异常:


prova.rb:4:in < main> ;':: main:Object(NameError)
的未定义局部变量或方法
greeting'

shell返回1

prova.rb:4:in <main>': undefined local variable or methodgreeting' for main:Object (NameError)
shell returned 1

但是,插值表达式无需命名捕获即可工作。例如:

However, the interpolated expression works without named captures. For example:

/(#{re})/ =~ str
$1
# => "hello"


推荐答案

命名捕获必须使用文字



您遇到了Ruby正则表达式库的一些限制。 Regexp#=〜方法限制命名捕获如下:

Named Captures Must Use Literals

You are encountering some limitations of Ruby's regular expression library. The Regexp#=~ method limits named captures as follows:


  • 如果正则表达式不是文字,则赋值不会发生。

  • regreg插值#{} 也会禁用分配。

  • 如果将regexp放在目录上,则不会发生分配。

  • The assignment does not occur if the regexp is not a literal.
  • A regexp interpolation, #{}, also disables the assignment.
  • The assignment does not occur if the regexp is placed on the right hand side.

您需要确定是要在常规表达式中使用命名捕获还是插值。您目前不能同时拥有两者。

You'll need to decide whether you want named captures or interpolation in your regular expressions. You currently cannot have both.

这篇关于为什么在Ruby中捕获命名组会导致生成“未定义的局部变量或方法”?错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆