Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with quantifiers and look-behind

Tags:

regex

ruby

### 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?

like image 469
edtsech Avatar asked Aug 13 '10 17:08

edtsech


People also ask

What is a negative Lookbehind?

A negative lookbehind assertion asserts true if the pattern inside the lookbehind is not matched.

What is regex look behind?

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.

What is a positive Lookbehind in regex?

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.

What is positive and negative lookahead?

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.


1 Answers

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.

like image 192
Borealid Avatar answered Nov 23 '22 18:11

Borealid