Ruby 后视断言 (1.9/2.0) 中是否存在错误? [英] Is there a bug in Ruby lookbehind assertions (1.9/2.0)?

查看:42
本文介绍了Ruby 后视断言 (1.9/2.0) 中是否存在错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么正则表达式 (?<=fo).* 不匹配 foo(而 (?<=f).*代码> 是)?

Why doesn't the regex (?<=fo).* match foo (whereas (?<=f).* does)?

"foo" =~ /(?<=f).*/m          => 1
"foo" =~ /(?<=fo).*/m         => nil

这似乎只在打开单行模式时发生(点匹配换行符);没有它,一切都好:

This only seems to happen with singleline mode turned on (dot matches newline); without it, everything is OK:

"foo" =~ /(?<=f).*/           => 1
"foo" =~ /(?<=fo).*/          => 2

在 Ruby 1.9.3 和 2.0.0 上测试.

Tested on Ruby 1.9.3 and 2.0.0.

在 Rubular 上查看

还有一些观察:

添加行尾锚点不会改变任何内容:

Adding an end-of-line anchor doesn't change anything:

"foo" =~ /(?<=fo).*$/m        => nil

但与惰性量词一起,它有效":

But together with a lazy quantifier, it "works":

"foo" =~ /(?<=fo).*?$/m       => 2

还有一些观察:

.+ 与其等效的 {1,} 一样工作,但仅在 Ruby 1.9 中(似乎这是唯一的行为差异在这种情况下两者之间):

.+ works as does its equivalent {1,}, but only in Ruby 1.9 (it seems that that's the only behavioral difference between the two in this scenario):

"foo" =~ /(?<=fo).+/m         => 2
"foo" =~ /(?<=fo).{1,}/       => 2

在 Ruby 2.0 中:

In Ruby 2.0:

"foo" =~ /(?<=fo).+/m         => nil
"foo" =~ /(?<=fo).{1,}/m      => nil

.{0,} 被破坏(在 1.9 和 2.0 中):

.{0,} is busted (in both 1.9 and 2.0):

"foo" =~ /(?<=fo).{0,}/m      => nil

但是 {n,m} 两者都适用:

"foo" =~ /(?<=fo).{0,1}/m     => 2
"foo" =~ /(?<=fo).{0,2}/m     => 2
"foo" =~ /(?<=fo).{0,999}/m   => 2
"foo" =~ /(?<=fo).{1,999}/m   => 2

推荐答案

这已被官方归类为作为错误并随后修复,以及关于多行字符串中 \Z 锚点的另一个问题.

This has been officially classified as a bug and subsequently fixed, together with another problem concerning \Z anchors in multiline strings.

这篇关于Ruby 后视断言 (1.9/2.0) 中是否存在错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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