Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

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

By the way, I have read the manual here.

like image 604
mays Avatar asked Feb 26 '10 11:02

mays


4 Answers

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.

Update 2022:

As of 2020 most major browsers except Safari have added support for lookbehind expressions. You can see the full support table here https://caniuse.com/js-regexp-lookbehind. However do note that other languages may not as noted in the original answer below. The updated quote from the linked manual is:

Finally, flavors like std::regex and Tcl do not support lookbehind at all, even though they do support lookahead.


Original answer:

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.

like image 105
Skilldrick Avatar answered Oct 25 '22 15:10

Skilldrick


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'
like image 25
Ignacio Vazquez-Abrams Avatar answered Oct 25 '22 16:10

Ignacio Vazquez-Abrams


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 :)

like image 20
Nick Craver Avatar answered Oct 25 '22 16:10

Nick Craver


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.

like image 33
Ikke Avatar answered Oct 25 '22 16:10

Ikke