Skip to content
PythonAdvanced Python Building Blocksbeginner30 min read

Regular Expressions

Master Python's re module to search, validate, extract, split, and replace text using regular-expression patterns.

In this lesson, you will learn

  • ✓Explain what regular expressions are and when they are useful.
  • ✓Write common regex patterns using character classes, quantifiers, anchors, and alternation.
  • ✓Explain why raw strings such as r'\d+' are commonly used for regex patterns.
  • ✓Distinguish between re.search(), re.match(), re.fullmatch(), and re.findall().
  • ✓Use capturing groups to extract structured information from text.
  • ✓Replace and split text with re.sub() and re.split().
  • ✓Handle unmatched patterns and test regex behavior against normal and boundary cases.

1. What is a regular expression?

A regular expression is a sequence of characters that describes a text pattern. Python's re module uses that pattern to search, match, extract, split, or replace parts of strings.

For example, if a message contains an order number such as Order 482, you could search for one or more digits instead of manually checking each character.

A regex pattern is not the text you are searching for. It is a description of the text you want to match. The pattern r'\d+' means one or more consecutive digits, so it can match 482 in Order 482.

Regular expressions are useful for log processing, extracting identifiers, checking simple input formats, cleaning text, and finding repeated structures. They are not automatically the best tool for every text-processing problem; ordinary string methods are often simpler for straightforward tasks.

Find digits in a string

Find digits in a string
python
import re
 
text = 'Order 482'
match = re.search(r'\d+', text)
 
if match:
print(match.group())
else:
print('No number')
Output
482

import re makes Python's regular-expression module available. The pattern r'\d+' looks for one or more consecutive digits. re.search() scans the string until it finds the first match. The match object is truthy when a match is found, so the if block runs. group() returns the complete matched text, which is the string '482'. print() displays 482 followed by a newline.

Note

Regex matches in Python are generally represented as strings when you call group() or findall() with a pattern that has no capturing groups. A digit match does not automatically become an integer; use int() if numeric arithmetic is required.

2. Raw strings and regex syntax

Backslashes have special meaning in regular expressions. For example, \d matches a digit, \w matches a word character, and \s matches whitespace.

Python string literals also interpret backslashes. Writing a pattern as a raw string, such as r'\d+', makes the pattern easier to read because Python does not process ordinary string escape sequences in the same way.

The r prefix does not change the regex engine. It changes how Python creates the string literal. Raw strings are a convention that helps prevent confusion between Python's string escaping and regex escaping.

Regex patterns combine literal characters and special syntax. The pattern 'cat' matches the literal text cat. The pattern r'\d+' matches a sequence of digits. A dot, '.', generally matches any character except a newline unless DOTALL behavior is enabled.

Match different character types

Match different character types
python
import re
 
text = 'Room 24 A'
print(re.findall(r'\d+', text))
print(re.findall(r'\w+', text))
print(re.findall(r'\s+', text))
Output
['24'] ['Room', '24', 'A'] [' ', ' ']

The first pattern finds one or more consecutive digits, producing ['24']. The second pattern finds runs of word characters, producing Room, 24, and A. The third pattern finds runs of whitespace. There are two individual spaces in the input. Each findall() call returns a list because the patterns contain no capturing groups.

Note

Useful character shortcuts include \d for digits, \w for word characters, and \s for whitespace. Their exact behavior can depend on flags and the character set. In ordinary Unicode string patterns, these shortcuts are Unicode-aware by default.

3. Character classes, quantifiers, and anchors

Character classes describe which characters are allowed at a position. For example, [abc] matches one character that is a, b, or c. A range such as [A-Z] matches one uppercase ASCII letter.

Quantifiers describe how many times the preceding pattern can occur. The symbol * means zero or more occurrences, + means one or more, and ? means zero or one. Braces specify a count or range, such as {3} for exactly three occurrences and {2,4} for between two and four occurrences.

Anchors specify a position rather than a character. The caret ^ generally matches the start of the string, and the dollar sign $ generally matches the end or, in some circumstances, just before a final newline. Use fullmatch() when the requirement is that the entire string match the pattern.

Alternation, written with |, means one alternative or another. Parentheses can group parts of a pattern and capture the text that matches those parts.

Use character classes and quantifiers

Use character classes and quantifiers
python
import re
 
print(bool(re.fullmatch(r'[A-Z]{2}\d{3}', 'AB123')))
print(bool(re.fullmatch(r'[A-Z]{2}\d{3}', 'A123')))
print(bool(re.fullmatch(r'colou?r', 'color')))
print(bool(re.fullmatch(r'colou?r', 'colour')))
Output
True False True True

[A-Z]{2} requires exactly two uppercase ASCII letters. \d{3} requires exactly three digits. AB123 satisfies both requirements, so the first result is True. A123 has only one uppercase letter, so the second result is False. The u? in colou?r makes the letter u optional. Both color and colour therefore match.

Note

Regex quantifiers are greedy by default: they try to match as much text as possible while allowing the overall pattern to succeed. Adding ? after a quantifier, as in .*?, makes that quantifier non-greedy.

4. search(), match(), fullmatch(), and findall()

Python provides several functions for different matching tasks. Choosing the correct function is as important as writing the pattern.

re.search(pattern, text) scans through the string and returns the first match anywhere in it, or None if no match exists.

re.match(pattern, text) attempts a match only at the beginning of the string. Without special flags, it does not scan forward to find a later occurrence.

re.fullmatch(pattern, text) succeeds only if the entire string matches the pattern. It is often a good fit for checking a simple format.

re.findall(pattern, text) returns all non-overlapping matches. Its return structure depends on capturing groups: no capturing groups gives full matched strings, one capturing group gives captured strings, and multiple capturing groups give tuples.

A successful search or match returns a match object, not the matched string directly. Use group() to obtain the matched text and start() or end() to inspect its position.

Compare search(), match(), and fullmatch()

Compare search(), match(), and fullmatch()
python
import re
 
text = 'ID: 482'
 
print(re.search(r'\d+', text).group())
print(re.match(r'\d+', text))
print(re.fullmatch(r'ID: \d+', text).group())
Output
482 None ID: 482

search() scans the entire string and finds 482. match() checks only the beginning, where the text starts with ID rather than a digit, so it returns None. fullmatch() succeeds because the entire string follows the pattern ID: followed by one or more digits. Calling group() on None would raise AttributeError, so check whether a match exists before calling group() on uncertain input.

Caution

Never call .group() on a possible None result without checking first. A failed search does not return an empty match object; it returns None.

5. Capturing groups and structured extraction

Parentheses can capture part of a match so that you can extract specific fields from text. For example, a pattern can capture a product code and a quantity separately.

A match object's group(0) is the complete match. group(1) is the first capturing group, group(2) is the second, and so on. The groups() method returns the captured groups as a tuple.

Non-capturing groups use the syntax (?:...). They group parts of a pattern without adding a captured value to the result.

Named capturing groups use the syntax (?P<name>pattern). They make extracted fields easier to understand and can be accessed using group('name') or groupdict().

Capture separate values

Capture separate values
python
import re
 
text = 'Product A12 quantity 7'
match = re.search(r'Product ([A-Z]\d+) quantity (\d+)', text)
 
if match:
print(match.group(0))
print(match.group(1))
print(match.group(2))
print(match.groups())
Output
Product A12 quantity 7 A12 7 ('A12', '7')

group(0) returns the complete matched text. The first capturing group ([A-Z]\d+) captures the product code A12. The second capturing group (\d+) captures the quantity as the string 7. groups() returns both captured strings in a tuple. If you need to perform arithmetic with the quantity, convert it using int(match.group(2)).

Note

A regex can confirm that a string has a YYYY-MM-DD shape, but it does not by itself validate month lengths, leap years, or whether the date actually exists. Use datetime.strptime() or another date-validation approach when calendar validity matters.

6. Replace and split text

re.sub() replaces occurrences matching a pattern. Its basic form is re.sub(pattern, replacement, text). The replacement can be a string or, for more advanced transformations, a function.

re.split() splits a string wherever a pattern matches. Unlike str.split(), it can use a pattern that recognizes several different separators.

The count parameter of re.sub() limits how many replacements are performed. If no count is supplied, all non-overlapping matches are replaced.

Be careful when using capturing groups with re.split(): captured separator groups may also appear in the resulting list.

Replace repeated whitespace

Replace repeated whitespace
python
import re
 
text = 'Python is\tfun'
cleaned = re.sub(r'\s+', ' ', text)
print(cleaned)
Output
Python is fun

The pattern \s+ matches one or more consecutive whitespace characters. The replacement is a single ordinary space. re.sub() replaces the run of spaces and the tab with one space. The resulting text is Python is fun.

Note

For simple splitting on one literal separator, str.split() is usually clearer. Use re.split() when the separator itself is described by a pattern.

7. Flags, case-insensitive matching, and boundaries

Regex flags modify how a pattern is interpreted. re.IGNORECASE, also written re.I, enables case-insensitive matching.

The word-boundary token \b matches a position between a word character and a non-word character, or at a suitable string boundary. It does not match a visible character.

re.MULTILINE changes the behavior of ^ and $ so they can match the beginning and end of individual lines within a string. re.DOTALL makes the dot match newline characters as well.

Flags should be selected because the task requires their behavior, not added automatically to every pattern.

Case-insensitive matching

Case-insensitive matching
python
import re
 
text = 'Python python PYTHON'
print(re.findall(r'python', text, flags=re.IGNORECASE))
Output
['Python', 'python', 'PYTHON']

The IGNORECASE flag allows the pattern python to match different letter cases. findall() returns all three matches in their original spelling.

8. Practical validation and common pitfalls

Regex is useful for validating simple formats, but matching a format does not always prove that the value is meaningful. For example, a pattern can require eight digits without proving that they represent a valid date.

Use re.fullmatch() for whole-string format checks. Using search() for validation may accidentally accept a valid-looking substring inside otherwise invalid input.

Be cautious with patterns such as .* and .+ because they can match more text than intended. Greedy quantifiers, nested repetition, and ambiguous alternatives can also make some patterns slow on particular inputs.

For user-supplied patterns or untrusted text, consider worst-case performance. Poorly designed patterns can exhibit catastrophic backtracking. Prefer simple patterns and avoid unnecessary nested ambiguous quantifiers.

Email addresses, URLs, telephone numbers, and other complex formats can have rules that are difficult to represent correctly with a short regex. Use a suitable parser or established validation library when the format requires more than a simple structural check.

Validate a simple product code

Validate a simple product code
python
import re
 
pattern = r'[A-Z]{2}-\d{4}'
 
for code in ['AB-1234', 'ab-1234', 'AB-123', 'XX-9999-extra']:
print(code, bool(re.fullmatch(pattern, code)))
Output
AB-1234 True ab-1234 False AB-123 False XX-9999-extra False

The pattern requires exactly two uppercase ASCII letters, a hyphen, and four digits. AB-1234 satisfies the full pattern. ab-1234 contains lowercase letters, so it fails. AB-123 has too few digits. XX-9999-extra contains extra text, so fullmatch() rejects it.

Caution

Do not treat a successful regex match as proof that external data is safe, authentic, or semantically valid. Regex is a text-pattern tool, not a replacement for appropriate parsing, validation, or security checks.

Common pitfalls to avoid

Real debugging lessons and exact syntax contrasts to avoid runtime bugs

#1 Using a normal string for a pattern without considering backslash escaping.

Why it happens: Backslashes have meaning in both Python string literals and regular expressions; raw strings reduce accidental double-escaping for many patterns.

Incorrect Approach
script.py
python
Using a normal string for a pattern without considering backslash escaping.
Correct Solution
script.py
python
Prefer raw strings such as r'\d+' for regex patterns. Remember that the r prefix affects Python string-literal processing, not regex semantics.

Key takeaway: Prefer raw strings such as r'\d+' for regex patterns. Remember that the r prefix affects Python string-literal processing, not regex semantics.

#2 Using re.match() when a match may occur anywhere in the string.

Why it happens: re.match() checks from the beginning of the string, while re.search() scans for a match anywhere in the string.

Incorrect Approach
script.py
python
Using re.match() when a match may occur anywhere in the string.
Correct Solution
script.py
python
Use re.search() to find the first occurrence anywhere, or re.findall() to collect all non-overlapping matches.

Key takeaway: Use re.search() to find the first occurrence anywhere, or re.findall() to collect all non-overlapping matches.

#3 Using re.search() to validate an entire input.

Why it happens: re.search() can succeed on only a substring, so use fullmatch() when the entire input must match the pattern.

Incorrect Approach
script.py
python
Using re.search() to validate an entire input.
Correct Solution
script.py
python
Use re.fullmatch() when the whole string must satisfy the pattern.

Key takeaway: Use re.fullmatch() when the whole string must satisfy the pattern.

#4 Calling group() after a search that might fail.

Why it happens: A search can return None when no match is found; check the result before calling group() to avoid AttributeError.

Incorrect Approach
script.py
python
Calling group() after a search that might fail.
Correct Solution
script.py
python
Check whether the returned match object is None before accessing group(), groups(), or other match details.

Key takeaway: Check whether the returned match object is None before accessing group(), groups(), or other match details.

#5 Assuming findall() always returns a list of complete matched strings.

Why it happens: findall() returns different shapes depending on capturing groups: full matches without groups, captured strings with one group, or tuples with multiple groups.

Incorrect Approach
script.py
python
Assuming findall() always returns a list of complete matched strings.
Correct Solution
script.py
python
Check the pattern's capturing groups. One group returns captured strings, while multiple groups return tuples.

Key takeaway: Check the pattern's capturing groups. One group returns captured strings, while multiple groups return tuples.

#6 Assuming a pattern that checks a format also validates the meaning of the value.

Why it happens: A regular expression can check a string's structure but may not verify semantic rules such as valid calendar dates or whether a username is available.

Incorrect Approach
script.py
python
Assuming a pattern that checks a format also validates the meaning of the value.
Correct Solution
script.py
python
Use an appropriate parser or validation logic for semantic rules such as valid calendar dates.

Key takeaway: Use an appropriate parser or validation logic for semantic rules such as valid calendar dates.

#7 Writing unnecessarily complicated patterns with nested greedy repetition.

Why it happens: Nested greedy quantifiers can cause excessive backtracking on some inputs; simplify patterns and use bounded or carefully designed matching when appropriate.

Incorrect Approach
script.py
python
Writing unnecessarily complicated patterns with nested greedy repetition.
Correct Solution
script.py
python
Prefer simpler patterns, test realistic inputs, and consider worst-case matching time when processing untrusted data.

Key takeaway: Prefer simpler patterns, test realistic inputs, and consider worst-case matching time when processing untrusted data.

Ready for hands-on challenges?

Test your skills with shuffled coding challenges in the Practice Arena.

Practice Arena →

Technical and placement interview questions

Frequently tested interview questions with detailed, full answers (click to expand)

Q1:What is a regular expression, and when would you use one?
Answer:
A regular expression is a pattern that describes text to search for or manipulate. In Python, the re module supports searching, validation, extraction, replacement, and splitting. Regex is useful when a pattern is more expressive than a simple string operation.
Q2:What is the difference between re.search(), re.match(), and re.fullmatch()?
Answer:
search() looks for the first match anywhere in the string. match() attempts a match only at the beginning. fullmatch() requires the entire string to match the pattern.
Q3:Why are raw strings commonly used for regex patterns?
Answer:
Regex syntax uses backslashes, and Python string literals also interpret backslashes. Raw strings such as r'\d+' make regex patterns easier to read by avoiding ordinary string-literal escape processing. The regex engine still interprets the pattern normally.
Q4:What is the difference between re.findall() and re.search()?
Answer:
search() returns a match object for the first match or None. findall() returns a list of all non-overlapping matches, with the result shape depending on whether the pattern has capturing groups.
Q5:What are capturing groups?
Answer:
Parentheses create capturing groups that store portions of a successful match. Use group(1), group(2), or groups() to access captured values. Named groups, such as (?P<year>\d{4}), make the captured fields easier to identify.
Q6:How can you replace repeated whitespace in Python?
Answer:
Use re.sub(r'\s+', ' ', text). The pattern matches each run of one or more whitespace characters and replaces it with a single space.
Q7:How do you perform case-insensitive regex matching?
Answer:
Pass flags=re.IGNORECASE, or flags=re.I, to a suitable re function such as re.search() or re.findall(). This lets the pattern match letters without requiring the same case.
Q8:How should you handle a failed regex search?
Answer:
A failed search returns None. Check the result before accessing group() or other match-object methods, otherwise an AttributeError can occur.
Q9:Can a regex validate an email address or date completely?
Answer:
A regex can check a chosen structural pattern, but a short pattern may not capture every rule of a complex format. A date-shaped string can still represent an impossible date. Use a suitable parser or validation library when semantic correctness matters.
Q10:What is a potential performance risk with complex regular expressions?
Answer:
Some patterns with ambiguous alternatives or nested repetition can trigger excessive backtracking on particular inputs. Prefer simpler patterns, test worst-case inputs, and be especially careful when processing untrusted text or patterns.

Key takeaways

  • Python's re module supports searching, matching, extraction, replacement, and splitting.
  • Raw strings such as r'\d+' make backslash-heavy regex patterns easier to read.
  • Character classes, quantifiers, groups, alternation, and anchors describe common text patterns.
  • search() finds a match anywhere, match() checks the beginning, and fullmatch() checks the whole string.
  • findall() returns all non-overlapping matches, with its output shape affected by capturing groups.
  • Use re.sub() to replace matching text and re.split() to split on pattern-based separators.
  • Check for None before calling match-object methods.
  • Regex format checks do not replace semantic validation, and complicated patterns can have performance risks.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: