Problem with quantifiers and look-behind

Viewed 4248
### 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"> 

I can't using quantifiers with look-behind?

3 Answers

For those who found this thread in 2022 with Ruby version >= 2.0, use \K:

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

Quoted from https://ruby-doc.org/core-3.1.2/doc/regexp_rdoc.html

\K - Uses an positive lookbehind of the content preceding \K in the regexp.

Related