tags:

views:

185

answers:

5

What does (?<=x) mean in regex?

By the way, I have read the manual here.

+2  A: 

From the Python re documentation:

(?<=...)

Matches if the current position in the string is preceded by a match for ... that ends at the current position. This is called a positive lookbehind assertion. (?<=abc)def will find a match in abcdef, since the lookbehind will back up 3 characters and check if the contained pattern matches. The contained pattern must only match strings of some fixed length, meaning that abc or a|b are allowed, but a* and a{3,4} are not. Note that patterns which start with positive lookbehind assertions will never match at the beginning of the string being searched; you will most likely want to use the search() function rather than the match() function:

>>> import re
>>> m = re.search('(?<=abc)def', 'abcdef')
>>> m.group(0)
'def'

This example looks for a word following a hyphen:

>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
Ignacio Vazquez-Abrams
+10  A: 

It's a positive lookbehind.

(?<=a)b (positive lookbehind) matches the b (and only the b) in cab, but does not match bed or debt.

You won't find it in any JavaScript manual because it's not supported in JavaScript regex:

Finally, flavors like JavaScript, Ruby and Tcl do not support lookbehind at all, even though they do support lookahead.

Skilldrick
thanks for the quick response.
mays
FYI, as of version 1.9 Ruby does support lookbehind.
Alan Moore
+1 For mentioning JavaScript’s support of this regular expression feature.
Gumbo
I know that Perl only works with fixed length lookbehind.
Brad Gilbert
+1  A: 

From regular-expressions.info:

Zero-width positive lookbehind. Matches at a position if the pattern inside the lookahead can be matched ending at that position (i.e. to the left of that position). Depending on the regex flavor you're using, you may not be able to use quantifiers and/or alternation inside lookbehind.

Ikke
+2  A: 

It's called a positive look behind, it's looking backwards for the character x, note this isn't supported by javascript though. For future reference, here's a better manual :)

Nick Craver
Thanks nick for the link
mays
+1 For mentioning JavaScript’s support of this regular expression feature.
Gumbo
+1  A: 

You are looking at a positive lookbehind assertion.

Otto Allmendinger
Thanks for the link. Helped.
mays