ruby - 为什么 =~ 运算符只是有时有副作用?

标签 ruby regex pattern-matching irb oniguruma

我注意到 Ruby/Oniguruma 中的副作用仅出现在 4 个看似等效的语句中的 1 个中。为什么变量是day009 中定义, 但不在 003 中, 005007

irb(main):001:0> r = /(?<day>\d\d):(?<mon>\d\d)/
=> /(?<day>\d\d):(?<mon>\d\d)/

irb(main):002:0> r =~ "24:12"
=> 0
irb(main):003:0> day
NameError: undefined local variable or method `day' 

irb(main):004:0> "24:12" =~ r
=> 0
irb(main):005:0> day
NameError: undefined local variable or method `day'


irb(main):006:0> "24:12" =~ /(?<day>\d\d):(?<mon>\d\d)/
=> 0
irb(main):007:0> day
NameError: undefined local variable or method `day'


irb(main):008:0> /(?<day>\d\d):(?<mon>\d\d)/ =~ "24:12"
=> 0
irb(main):009:0> day
=> "24"

nb#1:在所有四种情况下都是相同的正则表达式和相同的字符串。

nb#2:我已经验证了 MS Windows 和 Ubuntu Linux 中的行为。

最佳答案

当您调用 "24:12" =~ r 时你实际上调用"24:12".=~(r) .所以,String#=~只返回匹配开始的位置,如果没有匹配则返回 nil。

但是当你调用/(?<day>\d\d):(?<mon>\d\d)/ =~ "24:12"你实际上调用Regexp#=~

正如文档所说

If =~ is used with a regexp literal with named captures, captured strings (or nil) is assigned to local variables named by the capture names.

关于003呢? :

The assignment is not occur if the regexp is not a literal.

   re = /(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/
   re =~ "  x = y  "
   p lhs    # undefined local variable
   p rhs    # undefined local variable

The assignment is not occur if the regexp is placed at right hand side.
" x = y " =~ /(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/
p lhs, rhs # undefined local variable

关于ruby - 为什么 =~ 运算符只是有时有副作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6124489/

相关文章:

ruby - 从链接文本中提取带有 Nokogiri 的链接?

ruby-on-rails - 需要用户能够在 ruby​​ on rails 应用程序中连续下载 2 个文件

Javascript:将字符串路径转换为格式化数组

java - 使用java模式匹配删除单字母单词

Haskell:模式匹配、标识符和运算符

ruby-on-rails - 如何计算数据库中不同记录的总和

ruby-on-rails - 如何将 Nokogiri 中抓取的数据保存到 Rails 数据库中?

php - 正则表达式:去除非字母数字或标点符号

任何符号的Java正则表达式?

javascript - 在 JavaScript 中屏蔽最后 4 位数字