### 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"> 我不能在后视中使用量词吗?
发布于 2010-08-14 01:06:42
问题是Ruby不支持可变长度的lookbehinds。量词本身并不存在,但它们不能导致后视的长度是不确定的。
Perl有同样的限制,几乎所有主要的具有正则表达式的语言都有同样的限制。
尝试使用简单的match (\w*)\W*?o而不是lookbehind。
发布于 2015-03-17 22:57:24
我也遇到了同样的问题,Borealid的回答很好地解释了这个问题。
然而,这让我开始思考。也许量词不需要在后视中,但可以应用在后视本身上?
"hello".match(/(?<=\w*)o/)
# => SyntaxError: (irb):3: invalid pattern in look-behind: /(?<=\w*)o/
"hello".match(/(?<=\w)*o/)
# => #<MatchData "o">所以现在我们有了可变数量的恒定长度的lookbehinds。对我来说似乎绕过了这个问题。:)
https://stackoverflow.com/questions/3479131
复制相似问题