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
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
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
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
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
[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
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()
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
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
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
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
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
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
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
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
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.
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.
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.
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.
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.
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.
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.
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.
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?
Q2:What is the difference between re.search(), re.match(), and re.fullmatch()?
Q3:Why are raw strings commonly used for regex patterns?
Q4:What is the difference between re.findall() and re.search()?
Q5:What are capturing groups?
Q6:How can you replace repeated whitespace in Python?
Q7:How do you perform case-insensitive regex matching?
Q8:How should you handle a failed regex search?
Q9:Can a regex validate an email address or date completely?
Q10:What is a potential performance risk with complex regular expressions?
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.
Related Topics & Next Steps
4 Recommended LessonsStrengthen your Python foundation with these complementary core lessons: