re is Python's built-in module for working with regular expressions, which are sequences of characters that define a search pattern. In a sentence, re helps match, extract, or replace specific text patterns.
Regular expressions (regex) use special syntax to describe patterns. For example, \d{3} matches any three-digit number. When using re in Python, you import the module and apply functions like re.search() or re.findall() to sentences.
| Pattern | Description | Example |
|---|---|---|
\w |
Matches any word character (letter, digit, show) | re.findall(r'\w', 'Hello_123') returns ['H', 'e', 'l', 'l', 'o', '_', '1', '2', '3'] |
\s |
Matches any whitespace character | re.findall(r'\s', 'Hello world') returns [' '] |
\d |
Matches any digit | re.findall(r'\d', 'Call 555-1234') returns ['5', '5', '5', '1', '2', '3', '4'] |
Regex is often used to validate input, parse text, or find specific patterns. For instance, checking if an email address follows a standard format or extracting dates from unstructured text.
In a sentence, you might use regex to find all instances of a word or replace certain characters. For example, to replace all digits in a sentence with asterisks:
import re
sentence = "The price is 100 dollars."
result = re.sub(r'\d', '*', sentence)
print(result) # Output: "The price is *** dollars."
While Python's string methods like str.find() or str.replace() work for simple tasks, regex offers more flexibility and power. Regex can handle complex patterns that string methods cannot.
For example, to find all words starting with a capital letter in a sentence:
import re
sentence = "Python is fun. JavaScript is too."
result = re.findall(r'\b[A-Z]\w*', sentence)
print(result) # Output: ['Python', 'JavaScript']
This task would require multiple string operations without regex.
Suppose you have a sentence containing dates in various formats, and you want to extract them:
import re
sentence = "Meeting on 2023-10-05 or 05/10/2023?"
dates = re.findall(r'\d{4}-\d{2}-\d{2}|\d{2}/\d{2}/\d{4}', sentence)
print(dates) # Output: ['2023-10-05', '05/10/2023']
The regex pattern \d{4}-\d{2}-\d{2}|\d{2}/\d{2}/\d{4} matches both YYYY-MM-DD and MM/DD/YYYY formats.
According to the Python documentation, regular expressions are useful tools for pattern matching. They are widely used in data cleaning, text processing, and validation tasks.