What does (?<=x)
mean in regex?
By the way, I have read the manual here.
It's a positive lookbehind.
(?<=a)b
(positive lookbehind) matches theb
(and only theb
) incab
, but does not matchbed
ordebt
.
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.
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 inabcdef
, 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 thatabc
ora|b
are allowed, buta*
anda{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'
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 :)
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.
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