### 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?
A negative lookbehind assertion asserts true if the pattern inside the lookbehind is not matched.
Lookbehind has the same effect, but works backwards. It tells the regex engine to temporarily step backwards in the string, to check if the text inside the lookbehind can be matched there.
Lookbehind, which is used to match a phrase that is preceded by a user specified text. Positive lookbehind is syntaxed like (? <=a)something which can be used along with any regex parameter. The above phrase matches any "something" word that is preceded by an "a" word.
Positive lookahead: (?= «pattern») matches if pattern matches what comes after the current location in the input string. Negative lookahead: (?! «pattern») matches if pattern does not match what comes after the current location in the input string.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With