Regular expressions in Python – pattern matching for text using the re module.
What are regular expressions?
Regular expressions (regex or regexp) are character sequences that describe a search pattern. You can use them to check whether a string matches a pattern, replace matches, or split a string around a pattern.
The re module
Python’s built-in re module handles regex. Import it first:
import re
Basic patterns: matching characters
The simplest pattern matches a single character. For example, a matches the letter ‘a’:
pattern = r"a"
sequence = "Python"
print(re.search(pattern, sequence))
The r prefix marks a raw string, so backslashes pass through unchanged.
Matching multiple characters
Square brackets define a range of characters:
pattern = r"[a-e]"
sequence = "Hello"
print(re.search(pattern, sequence))
That matches any character from ‘a’ to ‘e’ in “Hello”.
Special characters
Some characters have special meanings in regex:
.(dot): matches any character except a newline.^: matches the start of a string.$: matches the end of a string.
pattern = r"^H.llo$"
sequence = "Hello"
print(re.match(pattern, sequence))
That matches strings starting with ‘H’, then any character, then ‘llo’.
Repetitions
You can repeat the preceding character:
*: zero or more repetitions.+: one or more repetitions.?: zero or one repetition.
pattern = r"Py.*n"
sequence = "Python Programming"
print(re.search(pattern, sequence))
Grouping
Parentheses () group sub-patterns. For example, (a|b|c)xz matches ‘a’, ‘b’, or ‘c’ followed by ‘xz’:
pattern = r"(Python|Java) Programming"
sequence = "Python Programming"
print(re.match(pattern, sequence))
Special sequences
Common shorthand sequences:
\d: any decimal digit; same as[0-9].\s: any whitespace character.\w: any alphanumeric character; same as[a-zA-Z0-9_].
pattern = r"\d\s\w+"
sequence = "2 Python"
print(re.match(pattern, sequence))
The findall function
findall returns every match in a string:
pattern = r"Py"
sequence = "Python Py Py"
print(re.findall(pattern, sequence))
Replacing strings
sub replaces pattern matches with another string:
pattern = r"Java"
replacement = "Python"
sequence = "I love Java"
print(re.sub(pattern, replacement, sequence))
Compiling regular expressions
If you reuse the same pattern, compile it once:
pattern = re.compile(r"Python")
sequence = "I love Python"
result = pattern.search(sequence)
Regex looks cryptic at first. Start with simple patterns on real strings – cleaning data, validating input, pulling bits from log files – and build up from there.

