Wrap a match with assertions on both sides
You can stack lookbehind and lookahead at the same position to assert what's on BOTH sides without consuming either. Useful for surgical extraction.
Example: extract value between fixed delimiters
"Get the text between [ and ], returning ONLY the inner text."
(?<=\[)[^\]]+(?=\])
(?<=\[)— assert opening bracket precedes[^\]]+— match the actual content (anything but a closing bracket)(?=\])— assert closing bracket follows
The match is just the inner content. The brackets are detected but excluded.
Same with capture group, less elegant
Without lookaround: \[([^\]]+)\] — match brackets, capture inner. Then access m.group(1). Functionally equivalent; readability cost moves between pattern and code.
When to prefer wrapped lookaround
Use wrapped lookaround when:
- You want
findallto return clean values without unpacking tuples. - You want the same pattern to reuse in
sedorripgrep --replacewhere capture groups are awkward. - The pattern is part of a more complex regex and you want one less capture slot to manage.
When to prefer capture groups
Use capture groups when:
- Your engine doesn't support lookbehind (Go, RE2).
- The lookbehind would need to be variable-width and your engine restricts.
- You want the surrounding text accessible for replacement (e.g., wrapping with brackets in sub).