C.W.K.
Stream
Lesson 04 of 10 · published

Positive Lookbehind — (?<=...)

~8 min · lookbehind, positive

Level 0Pattern-Curious
0 XP0/90 lessons0/15 achievements
0/100 XP to next level100 XP to go0% complete

Assert that something precedes, without including it

(?<=...) is lookahead's mirror image: "at the current position, the pattern inside the lookbehind matches the text immediately BEFORE this position." Same zero-width semantics — the matched text isn't part of the capture.

The classic use: extract values after a marker

Extract the price after '$': (?<=\$)\d+(\.\d+)?. The lookbehind asserts a '$' precedes; the actual match is just the number. Without it, you'd capture '$19.99' and slice off the '$' in code.

Same pattern works for any prefix marker: extract user IDs after 'user_', extract dates after 'on ', extract whatever-comes-after-X without including X.

The width restriction (HUGE)

Most engines require the lookbehind pattern to be fixed-width — every alternative inside must match the same number of characters.

  • Java, .NET, Python's re: Fixed-width only. (?<=cat) works (3 chars); (?<=cat|elephant) may fail or behave wrong.
  • Python's regex module, PCRE 8+: Variable-width allowed.
  • JavaScript: Variable-width since ES2018.
  • RE2 / Go: Lookbehind NOT supported at all.

This is the most fragmented feature in regex. Always check your engine's docs before relying on lookbehind.

Code

Lookbehind patterns·python
import re

# Extract price after '$'
re.findall(r'(?<=\$)\d+(?:\.\d+)?', 'paid $19.99 not 20 but $5')
# ['19.99', '5']

# Extract IDs after 'user_'
re.findall(r'(?<=user_)\w+', 'user_alice signed in, user_bob too')
# ['alice', 'bob']

# After 'on ' get the date (with fixed-width pattern)
re.findall(r'(?<=on )\d{4}-\d{2}-\d{2}', 'logged on 2026-05-04 received')
# ['2026-05-04']

# Variable-width — works in Python's third-party 'regex' module
# import regex
# regex.findall(r'(?<=cat|elephant) sat', 'the cat sat the elephant sat')
# ['sat', 'sat']  — works

# In Python's built-in 're', this might raise an error or behave unexpectedly

External links

Exercise

Extract every URL path that comes after 'GET ' in an Apache log line. The path is the second field. Use lookbehind to anchor to 'GET ' and match the path itself. Test on a sample log line.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.