Python RegEx
A RegEx (Regular Expression) is a sequence of characters that forms a search pattern. Python has a built-in re module that you can use to check if a string contains a specified pattern, extract matching text, or replace substrings.
1. Searching a Pattern with re.search()
re.search() scans the string and returns a Match object if there is a match anywhere in the string, or None if no match is found:
import re
text = "Learn Python programming at Expertsjava."
match = re.search(r"Python", text)
if match:
print("Found match:", match.group(), "at index:", match.start())
else:
print("No match found")
2. Finding All Matches with re.findall()
re.findall() returns a list containing all non-overlapping matches of a pattern in the string:
import re
log = "Order #104 placed on 2026-11-22 for 2 items."
digits = re.findall(r"\d+", log)
print("All numbers found:", digits) # Output: ['104', '2026', '11', '22', '2']
3. Replacing Text with re.sub()
re.sub() replaces all occurrences of a pattern with a replacement string:
import re
sentence = "Java is great. Java is widely used."
updated = re.sub(r"Java", "Python", sentence)
print(updated) # Output: Python is great. Python is widely used.
4. Common RegEx Metacharacters & Sequences
Here are a few frequently used pattern tokens in Python regular expressions:
import re
# \d -> Matches any digit (0-9)
# \w -> Matches word characters (letters, digits, underscore)
# \s -> Matches whitespace (spaces, tabs)
# + -> One or more repetitions
# ^ / $ -> Start and end of string
code = "PY_2026"
is_valid = bool(re.fullmatch(r"[A-Z]{2}_\d{4}", code))
print("Valid format:", is_valid) # Output: True
Tip: Always write regex patterns as raw strings (
r"...") so Python does not treat backslashes like \d or \s as string escape sequences.