量词和后顾问题。

18
### Ruby 1.8.7 ###

require 'rubygems'
require 'oniguruma' # for look-behind

Oniguruma::ORegexp.new('h(?=\w*)')
# => /h(?=\w*)/

Oniguruma::ORegexp.new('(?<=\w*)o')
# => ArgumentError: Oniguruma Error: invalid pattern in look-behind

Oniguruma::ORegexp.new('(?<=\w)o')
# => /(?<=\w)o/


### Ruby 1.9.2 rc-2 ###

"hello".match(/h(?=\w*)/)
# => #<MatchData "h">

"hello".match(/(?<=\w*)o/)
# => SyntaxError: (irb):3: invalid pattern in look-behind: /(?<=\w*)o/

"hello".match(/(?<=\w)o/)
# => #<MatchData "o"> 

我不能在后顾断言中使用量词?

3个回答

28

问题是Ruby不支持可变长度的回顾前缀。量词本身并没有被禁用,但它们不能导致回顾前缀的长度是不确定的。

与正则表达式相关的主要编程语言大多数都有这个限制,包括Perl。

尝试使用直接匹配(\w*)\W*?o代替回顾前缀。


6

我曾经也为同一个问题苦恼,Borealid的回答很好地解释了这个问题。

不过,这让我想到了另一个问题。也许量词不需要在后顾之后内部,而是可以应用于后顾本身?

"hello".match(/(?<=\w*)o/)
# => SyntaxError: (irb):3: invalid pattern in look-behind: /(?<=\w*)o/

"hello".match(/(?<=\w)*o/)
# => #<MatchData "o">

现在我们有了一个可变数量的恒定长度回溯。对我来说似乎可以绕过这个问题。 :)


0

对于那些在2022年使用Ruby版本>= 2.0的人,请使用\K

$ ruby -e 'p ARGV.first.match(/h\K\w*/)' hello
#<MatchData "ello">

引用自 https://ruby-doc.org/core-3.1.2/doc/regexp_rdoc.html

\K - 使用正则表达式中 \K 之前的内容进行正向回顾后断言。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接