### 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">
Run Code Online (Sandbox Code Playgroud)
我不能使用带有后视的量词吗?
Bor*_*lid 27
The issue is that Ruby doesn't support variable-length lookbehinds. Quantifiers aren't out per se, but they can't cause the length of the lookbehind to be nondeterministic.
Perl has the same restriction, as does just about every major language featuring regexes.
Try using the straightforward match (\w*)\W*?o instead of the lookbehind.
我正在敲打同样的问题,Borealid的答案很好地解释了这个问题.
然而,这让我思考.也许量词并不需要是里面的回顾后,但在回顾后应用本身?
"hello".match(/(?<=\w*)o/)
# => SyntaxError: (irb):3: invalid pattern in look-behind: /(?<=\w*)o/
"hello".match(/(?<=\w)*o/)
# => #<MatchData "o">
Run Code Online (Sandbox Code Playgroud)
所以现在我们有一个可变数量的恒定长度的lookbehinds.似乎为我绕过了这个问题.:)