Python Regular Expressions (Regex)
Posted on June 1, 2024 (Last modified on June 8, 2024) • 2 min read • 258 wordsMaster regular expressions in Python for powerful text processing, including pattern matching, search, and replace operations.
Regular expressions (regex) are powerful tools for text processing. This guide covers pattern matching, search, and replace operations using Python’s re
module.
re
Module
import re
pattern = r"\bhello\b"
text = "hello world"
if re.search(pattern, text):
print("Match found!")
Find all occurrences of a pattern.
pattern = r"\d+"
text = "There are 123 apples and 45 bananas."
matches = re.findall(pattern, text)
print(matches) # Output: ['123', '45']
Replace occurrences of a pattern.
pattern = r"\d+"
text = "There are 123 apples and 45 bananas."
new_text = re.sub(pattern, "number", text)
print(new_text) # Output: There are number apples and number bananas.
pattern = r"(\d+)\s(apples|bananas)"
text = "123 apples and 45 bananas"
matches = re.findall(pattern, text)
print(matches) # Output: [('123', 'apples'), ('45', 'bananas')]
Groups allow you to extract specific parts of the match.
match = re.search(pattern, text)
if match:
quantity = match.group(1)
fruit = match.group(2)
print(f"Quantity: {quantity}, Fruit: {fruit}") # Output: Quantity: 123, Fruit: apples
pattern = r"(?P<quantity>\d+)\s(?P<fruit>apples|bananas)"
text = "123 apples and 45 bananas"
for match in re.finditer(pattern, text):
print(f"Quantity: {match.group('quantity')}, Fruit: {match.group('fruit')}")
Named groups provide a way to access captured groups by name.
match = re.search(pattern, text)
if match:
quantity = match.group('quantity')
fruit = match.group('fruit')
print(f"Quantity: {quantity}, Fruit: {fruit}")
Mastering regular expressions can greatly enhance your text processing capabilities in Python. Practice using regex for pattern matching, search, and replace operations to handle complex text manipulation tasks.