Introduction

Lookbehinds are a powerful and versatile feature of regular expressions that enable you to match patterns in text that come before a specific position. This is extremely handy when you need to extract a substring from the middle of a text that is preceded by a specific set of characters or expressions. In this tutorial, we will introduce you to the concept of lookbehind in regex, show you how to use it in Python, and walk you through some practical examples that demonstrate its capabilities. By the end of this tutorial, you should have a solid understanding of how Regex Lookbehind works and how to leverage it in your Python code. So, let's get started!

Table of Contents :

  • Python Regex Lookbehind
  • Negative Lookbehind

Python Regex Lookbehind :

  • Lookbehind is a feature of Python's regular expression syntax that allows you to match a pattern only if it is preceded by another pattern.
  • Lookbehind is denoted by the  (?<=  sequence, which follows the pattern to be matched.
  • Code Sample :

import re

# Lookbehind example
text = "The quick brown fox jumps over the lazy dog."
pattern = r"(?<=quick\s)\b\w+\b"
result = re.findall(pattern, text)
print(result)  


# Output: 
['brown']



Negative Lookbehind :

  • Negative lookbehind is a feature of Python's regular expression syntax that allows you to match a pattern only if it is not preceded by another pattern.
  • Negative lookbehind is denoted by the  (? 
  • Code Sample :

import re

# Negative lookbehind example
text = "The quick brown fox jumps over the lazy dog."
pattern = r"\b(?"


Prev. Tutorial : Lookahead