RegEx (Regular Expressions) are patterns used to search, match, and manipulate text. In Python, the re module provides powerful tools for working with these patterns so you can find substrings, validate input, and transform text efficiently.
Common use cases include validating email addresses, extracting specific data from logs, finding all occurrences of a word, and performing complex search-and-replace operations.
re module – Built-in Python module that contains regex functions.r that keeps backslashes as-is (e.g., r"\d+").\d, \w, ., *, ^, $.Some commonly used regex pieces in Python:
\d – Any digit (0–9)\w – Any word character (letters, digits, underscore)\s – Any whitespace (space, tab, newline)^ – Start of the string$ – End of the string.* – Any character (.) repeated zero or more times (*)Always prefer using raw strings for patterns, for example: r"\d{3}-\d{2}-\d{4}". This avoids conflicts with Python's own escape sequences.
re.search()
# Import the regular expressions module
import re
# Text in which we want to search for the pattern
text = "The rain in Spain"
# Search for the word 'Spain' in the text
match = re.search("Spain", text)
# If a match is found, print it
if match:
print("Found:", match.group())
re.findall()
import re
text = "cat bat rat mat"
matches = re.findall(r"\b\w{3}\b", text)
print(matches) # ['cat', 'bat', 'rat', 'mat']
re.sub()
import re
text = "I like cats"
new_text = re.sub("cats", "dogs", text)
print(new_text) # I like dogs
Code: Basic search example with re.search().
What happens:
"Spain" is searched inside the string "The rain in Spain".re.search() scans the entire string until it finds the first match.None.match.group() returns the actual matched text.Expected output:
Found: Spain
r"pattern") to avoid escaping backslashes manually.re.findall() when you need to collect multiple matches at once.re.search() and re.match() carefully:
re.match() checks only at the beginning of the string.re.search() scans the whole string for the first match.re.findall().re.sub() to censor bad words by replacing them with ***.re.split() and an appropriate pattern.