15

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

By the way, I have read the manual here.

Skilldrick
  • 69,215
  • 34
  • 177
  • 229
mays
  • 347
  • 1
  • 3
  • 11

5 Answers5

15

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.

jjspace
  • 178
  • 2
  • 11
Skilldrick
  • 69,215
  • 34
  • 177
  • 229
2

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
  • 776,304
  • 153
  • 1,341
  • 1,358
2

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
  • 623,446
  • 136
  • 1,297
  • 1,155
1

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
  • 99,403
  • 23
  • 97
  • 120
1

You are looking at a positive lookbehind assertion.

Otto Allmendinger
  • 27,448
  • 7
  • 68
  • 79