Python Regular Expressions: Lookahead and lookbehind examples

Python Regular Expressions: Lookahead and lookbehind examples

Last updated:
Table of Contents

Unless otherwise stated, examples use Python 3+.

For all the other use cases for regular expressions in Python, see Python Regular Expressions: Examples & Reference

Lookbehind

TEMPLATE: (?<=PATTERN)

Match pattern if it is immediately preceded by something.

Example pattern: "bar" only if it's preceded by "foo"

import re

# replace "bar" with "BAR" if it IS preceded by "foo"
pattern = "(?<=foo)bar"
replacement = "BAR"

string = "foo bar foobar"

re.sub(pattern,replacement,string)
# 'foo bar fooBAR'

Negative lookbehind

TEMPLATE: (?<!PATTERN)

Match pattern if it is not immediately preceded by something.

Example pattern: "bar" if it's NOT preceded by "foo"

import re

# replace "bar" with BAR if it is NOT preceded by "foo"
pattern = "(?<!foo)bar"
replacement = "BAR"
string = "foo bar foobar"

re.sub(pattern, replacement, string)
# 'foo BAR foobar'

Lookahead

TEMPLATE: (?=PATTERN)

Match pattern if it is immediately followed by something else.

Example pattern: "foo" only if it's followed by "bar"

import re

# replace "foo" only if it IS followed by "bar"
pattern = "foo(?=bar)"
replacement = "FOO"
string = "foo bar foobar"

re.sub(pattern,replacement,string)
# 'foo bar fooBAR'

Negative Lookahead

TEMPLATE: (?!PATTERN)

Match pattern if it is not immediately followed by something else.

Example pattern: "foo" only if it's NOT followed by "bar"

import re

# replace "foo" only if it is NOT followed by "bar"
pattern = "foo(?!bar)"
replacement = "FOO"
string = "foo bar foobar"

re.sub(pattern,replacement,string)
# 'FOO bar foobar'