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! 📝
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 checks if a certain pattern follows the current position in a string without including it in the match.
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.
(?<=...) 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.
(?<=...) checks if the pattern comes before the current position.(?<!...) checks if the pattern does not come before the current position.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.
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.
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.
Which Regular Expression technique is used to check if a certain pattern comes immediately before the current position in a string?
Happy coding! 💡