Python Tutorial: Lookahead and Lookbehind 🎯

beginner
14 min

Python Tutorial: Lookahead and Lookbehind 🎯

Welcome to the Python Tutorial on Lookahead and Lookbehind! In this lesson, we'll dive deep into these powerful Regular Expression techniques, making your code more flexible and efficient. By the end of this tutorial, you'll be able to tackle complex text processing tasks with ease. Let's get started! 📝

What are Lookahead and Lookbehind? 💡

Lookahead and Lookbehind are Regular Expression (regex) techniques that allow you to check for a pattern without including it in the match. They're essential tools when working with complex text patterns and can make your code more maintainable and flexible.

Lookahead ((?=...))

Lookahead checks if a certain pattern follows the current position in a string without including it in the match.

python
import re text = "python3 is the best language for web development" match = re.search(r'(?=best) language', text) print(match) # Returns <re.Match object; span=(19, 29), match=' language'>

In the above example, the regex pattern (?=best) language checks if "best" is found in the string, but it's not included in the match.

Lookbehind ((?<=...) and (?<!...))

Lookbehind checks if a certain pattern occurs immediately before the current position in a string without including it in the match. There are two types of lookbehinds: positive and negative.

  • Positive lookbehind (?<=...) checks if the pattern comes before the current position.
  • Negative lookbehind (?<!...) checks if the pattern does not come before the current position.
python
import re text = "increase-salary-2022" match = re.findall(r'(?<=-)\w+', text) print(match) # Returns ['salary', '2022']

In the above example, the regex pattern (?<=-)\w+ checks for words that come immediately before a hyphen.

Practical Uses 💡

  • Validating input data
  • Parsing HTML and XML
  • Working with dates and numbers
  • Extracting specific patterns from logs and text files

Advanced Examples 💡

Lookahead with Greedy Quantifiers

python
import re text = "I have 3 apples and 2 oranges. I have 4 more apples." match = re.search(r'(\d+) (\w+)s\s+(?=\d+\smore\s\w+s|$)', text) print(match.group()) # Returns '3 apples'

In this example, we use a greedy quantifier + followed by a lookahead to extract the number and fruit from the sentence. The lookahead ensures we don't match any future occurrences of the same pattern.

Negative Lookbehind for HTML Parsing

python
import re html = '<div class="item">Apple - Fruit</div><div class="item">Orange - Juice</div>' match = re.findall(r'(?<!<div).*?(?=</div>)', html, re.DOTALL) print(match) # Returns [' Apple - Fruit', ' Orange - Juice']

In this example, we use a negative lookbehind to extract content between <div> and </div> tags without including the tags themselves.

Quiz 💡

Quick Quiz
Question 1 of 1

Which Regular Expression technique is used to check if a certain pattern comes immediately before the current position in a string?

Happy coding! 💡