- Learn
- Computer Science & IT
- Programming
- Intermediate Python
- Python Regular Expressions
Python Regular Expressions
Text Processing and Regular Expressions in Python
re module to find, capture, replace and split text. You then check user input against required formats, parse lines of a log file into records, tidy messy text with string methods and patterns, and normalize Unicode so that accented characters stored in different ways compare equal.IntermediateLesson 4 of 9 in Intermediate Python Course
What you will learn
- Read and write patterns that describe the text you are looking for: literal characters, character classes, quantifiers, anchors and alternatives.
- Decide when to use a regular expression and write it as a raw stringRecognize when a fixed-string method is enough and when a pattern is needed, escape special characters, and write patterns as raw strings.
- Match one character from a set with character classesUse square-bracket classes, ranges, negated classes, the dot and the shorthand classes, and know how they treat Unicode text.
- Repeat parts of a pattern with quantifiersUse quantifiers for optional and repeated parts, tell greedy from lazy matching, and avoid patterns that make the engine backtrack endlessly.
- Anchor matches to positions and choose between alternativesTie a match to the start or end of a string, a line or a word, and write alternatives with the right precedence and order.
- Decide when to use a regular expression and write it as a raw string
- Choose the right function for the question you are asking, read the Match objects it returns, collect every match, and reuse compiled patterns with flags.
- Choose between search, match and fullmatch and read Match objectsPick the function that matches where the pattern must fit, handle the None result safely, and read the text and position of a match.
- Find every match with findall and finditerCollect all matches as strings or as Match objects, predict the shape of findall's result, and extract items such as words, numbers and addresses.
- Compile patterns and change matching with flagsStore reusable patterns as compiled Pattern objects, change matching with flags passed safely by keyword, write readable verbose patterns, and read pattern errors.
- Choose between search, match and fullmatch and read Match objects
- Use parentheses to capture, name and reuse parts of a match, test the surrounding text without consuming it, and turn lines of text into structured records.
- Capture parts of a match with numbered and named groupsMark the parts of a pattern you need with capturing groups, read them by number or name, and handle optional and repeated groups.
- Group without capturing, refer back to groups and look around a matchUse non-capturing groups, backreferences and lookahead or lookbehind assertions to express conditions that a plain sequence cannot.
- Turn lines of text into structured recordsRead a text file line by line, parse each line with a compiled pattern into a dictionary, count and summarize the results, and handle lines that do not fit.
- Capture parts of a match with numbered and named groups
- Check that user input and data fields have the required format, and combine pattern checks with code that tests meaning, ranges and limits.
- Check that a whole string has the required formatUse fullmatch to test complete strings, turn a written format rule into a pattern, normalize input first, and test the validator on good, bad and edge cases.
- Combine regex checks with code for meaning and limitsRecognize what a pattern cannot check, add code for dates, ranges and lengths, accept reasonable variants, and keep validation readable and safe.
- Check that a whole string has the required format
- Replace and split text with regular expressions, clean inconsistent text with string methods and patterns, and normalize Unicode so that the same characters stored in different ways compare equal.
- Replace text with re.sub and split it with re.splitSubstitute matches with fixed text, group references or a function, count replacements, and split text on separators that vary.
- Clean messy text with string methods and regular expressionsDecide on a target form, then trim, collapse whitespace, unify case, replace or remove characters and standardize values in a tested cleaning function.
- Normalize Unicode text before comparing and matchingExplain why identical-looking strings can differ, apply the four normalization forms with unicodedata, and build accent-insensitive and case-insensitive keys.
- Replace text with re.sub and split it with re.split
Python Regular Expressions study guide
1Write regular expression patterns
Patterns describe the shape of text, from a single permitted character to a repeated field or a choice of complete forms. You start by choosing between string methods and a regex, then learn how Python passes a pattern to the engine. Character classes, repetition, and position tests build on that foundation. Reading these pieces in order makes it possible to predict what a pattern accepts before applying it to a long input.
1.1 Choose a text tool and write a literal pattern
A regular expression describes a set of strings. It is useful when the text you want can vary in a predictable way: a run of digits, an identifier followed by a colon, or a date written with fixed separators.
Start with the simplest text tool
For fixed text, use a string operation. "warning" in line checks for a substring, line.startswith("Status:") checks a prefix, and line.replace("-", "") removes literal hyphens. These calls make the task easy to see. A pattern becomes useful when you need a rule such as "one or more digits" instead of a known piece of text.
Import the standard library module with import re. Most ordinary characters in a pattern match themselves. The pattern cat finds "cat" even inside "concatenate"; it has no built-in idea of a complete word. Matching is case-sensitive by default, so the same pattern does not find "Cat".
Keep the two kinds of escaping separate
Python reads a string literal first. Then the regex engine reads the resulting string as a pattern. A raw string keeps backslashes available for this second stage:
import re
text = "A cat naps."
m = re.search(r"\bcat\b", text)
if m:
print(m.group()) # cat
In an ordinary string, "\b" becomes a backspace character before re sees it. In r"\b", the engine receives the backslash and the letter "b", which it reads as a word boundary. Ordinary literals containing unrecognized escapes such as "\d" trigger a SyntaxWarning in Python 3.12 and later. Use raw literals for patterns consistently.
Raw syntax preserves the pattern; it does not make the pattern literal. The metacharacters . ^ $ * + ? { } [ ] \ | ( ) still have regex meanings. For a literal period write r"\."; for a literal plus sign write r"\+"; for an opening parenthesis write r"\(".
For example, r"3.14" matches "3914" because the dot accepts any one character except a newline. r"3\.14" requires the period and matches "3.14".
Search, then inspect the result
re.search(pattern, text) returns a Match object for the first match or None if none exists. Test the result before asking for its text:
m = re.search(r"ship", "Order 66 shipped")
if m:
print(m.group()) # ship
print(m.start()) # 9
The match starts at index 9, counting from zero. This succeeds on part of "shipped"; search looks anywhere and accepts a matching substring. A whole-input test uses re.fullmatch.
re.findall collects matches from left to right without overlap. In "banana", r"an" yields ['an', 'an'], but r"ana" yields only ['ana']: the second possible occurrence starts inside the first match.
Search for text supplied by someone else
A user's text can contain metacharacters. Build its literal pattern with re.escape:
needle = "1+1=2"
m = re.search(re.escape(needle), "Check 1+1=2 now")
re.escape(needle) produces 1\+1=2, so the plus sign cannot become a quantifier. If all you need is a literal substring test, needle in text is still simpler.
Key Takeaways
- Use string methods for fixed text and regex for a varying structure.
- Raw string literals preserve backslashes for the regex engine.
- Escape metacharacters to match them literally; use
re.escapefor supplied text. searchreturns the first Match orNone;findallcollects non-overlapping matches.
1.2 Describe the characters a pattern accepts
A character class matches one character chosen from a set. Use it to say what may appear at a position without writing a separate pattern for every possible string.
Sets, ranges, and exceptions
[aeiou] matches one lowercase vowel. In gr[ae]y, the class accepts either "a" or "e" in that position. A range uses code-point order: [0-9] accepts one ASCII digit, [a-z] one unaccented lowercase letter, and [A-Za-z0-9] one ASCII letter or digit.
Place a literal hyphen first or last, as in [-+], or escape it as \-. A hyphen between two endpoints usually forms a range. Inside a class, most other metacharacters become ordinary: [.?*] matches a period, question mark, or asterisk. Take care with ], \, a leading ^, and a range-forming -.
A caret immediately after [ negates the class. [^0-9] accepts one character other than an ASCII digit, including a newline. In [a^b], the caret is literal. Negation changes the accepted set; it does not mean "skip this character."
Read one position at a time
import re
print(re.findall(r"[A-Z]\d", "Rooms A7, B12 and c3"))
# ['A7', 'B1']
The first item requires one uppercase ASCII letter. The next requires one decimal digit. "A7" fits both positions. In "B12", only "B1" is needed for a match, leaving "2" outside it. "c3" fails because lowercase "c" is absent from [A-Z]. A class never means a whole run on its own; add a quantifier when a position may repeat.
Use shorthand classes deliberately
For Python string patterns:
\dmatches a Unicode decimal digit;\Dmatches a character that is not one.\wmatches any character for whichstr.isalnum()is true, plus_;\Wmatches its complement.\smatches whitespace, including spaces, tabs, and newlines;\Smatches non-whitespace.
The word class includes accented letters, letters from other scripts, and numeric characters such as "½". It does not mean only English letters, and it includes the underscore. Shorthands also work inside a class: [\w.-] adds a literal period and hyphen to the word characters.
print(re.findall(r"\w+", "café naïve")) # ['café', 'naïve']
print(re.findall(r"[a-z]+", "café")) # ['caf']
The second result ends before "é" because [a-z] is a specific ASCII range. Similarly, \d accepts "٣" and "3" as decimal digits. Even int("٣") succeeds and returns 3, so conversion alone does not enforce ASCII input.
Use [0-9] when an interface requires the characters "0" through "9". re.ASCII also restricts \d, \w, \s, and word boundaries to ASCII behavior.
Know what the dot leaves out
. accepts any single character except a newline. re.DOTALL makes it accept newlines too. A negated class such as [^,] already accepts a newline unless the newline is explicitly excluded. Choose the accepted set based on the text's structure, especially when a pattern must stay on one line.
Key Takeaways
- A class matches exactly one character; a quantifier repeats it.
- A leading caret negates a class, while a hyphen can create a range.
\d,\w, and\suse Unicode rules for string patterns.\wincludes alphanumeric characters and_, including numeric characters such as "½".- Use
[0-9]orre.ASCIIfor ASCII digit rules. - The dot excludes newlines unless
re.DOTALLis enabled.
1.3 Control repetition and backtracking
Quantifiers describe how often the item directly before them repeats. Their placement controls both the accepted text and how the engine searches for a match.
Choose a repetition rule
* means zero or more, + one or more, and ? zero or one. Braces give counts: {m} exactly m, {m,n} m through n, {m,} at least m, and {,n} at most n. Keep spaces out of the braces: a{1, 3} matches literal text, not one through three copies of "a".
The repeated item can be a character, class, escape, or group. ab+ repeats only "b", producing matches such as "abbb". (ab)+ repeats the pair, so it accepts "abab". colou?r accepts the two spellings produced by including or omitting "u".
import re
print(re.findall(r"\d{2,4}", "7 42 2024 123456"))
# ['42', '2024', '1234', '56']
The single "7" is too short. The six-digit run does not fail as a unit: this is a search for substrings, so it supplies a four-digit match and then a two-digit match. A length limit on each match is different from a whole-input validation rule.
Greedy and lazy describe search choices
A greedy quantifier takes as much text as it can while the rest of the pattern can still succeed. In r"<.+>" on "bold", .+ runs to the last possible closing delimiter, so the match is the whole string.
Adding ? after a quantifier makes it lazy: *?, +?, ??, or {m,n}?. re.findall(r"<.+?>", "<b>bold</b>") returns ['<b>', '</b>']. The engine tries a short repetition first and extends it when necessary. Lazy does not mean "always one character."
When a delimiter ends a field, a negated class can express the rule directly. <[^>]+> requires one or more characters other than ">" inside the delimiters. On this input it gives the same two results without relying on a lazy dot.
Trace what happens when a suffix fails
For r"\d+0" on "12300", the greedy \d+ first takes every digit. The final literal "0" then has nothing to match. The engine backtracks: it gives back the last digit so the suffix can use it. The whole match is still "12300".
A pattern that allows zero repetitions can produce empty matches. re.findall(r"\d*", "a1") returns ['', '1', '']. The first and last matches contain no digits. Use + when a match must include at least one.
Remove ambiguous repetition
Nested repetition such as (a+)+b can split a run of "a" characters in many ways. When the final "b" is missing, trying those divisions can take exponential time: catastrophic backtracking. For untrusted input, check length before matching and avoid repeated groups whose contents can repeat over the same text.
Python 3.11 added possessive quantifiers and atomic groups. a++b never gives back an "a"; (?>a+)+b discards choices from the inner run after it succeeds. Placing the atomic group around the entire failing expression, (?>(a+)+b), leaves the expensive internal search in place. The atomic boundary must protect the repetition that creates the choices.
Key Takeaways
- A quantifier applies only to the item immediately before it.
- Greedy repetition can give back text; lazy repetition expands only as needed.
- Zero-length matches are real matches, so use
+when content is required. - Avoid ambiguous nested repetition and limit untrusted input length.
- Possessive quantifiers and correctly placed atomic groups prevent backtracking within the protected part.
1.4 Place a match and group its alternatives
Anchors and word boundaries test positions without consuming characters. Alternation chooses between patterns. Together they let you say where a match belongs and which complete forms are acceptable.
String edges and line edges
^ matches the start of a string. $ matches its end or the position just before a final newline. \A matches only the start of the string, and \Z only the absolute end. Python 3.14 added \z with the same meaning as \Z.
import re
print(bool(re.search(r"end$", "the end\n"))) # True
print(bool(re.search(r"end\Z", "the end\n"))) # False
The dollar anchor does not consume the newline; it can succeed before it. That detail matters in input validation. re.fullmatch provides a direct way to require that the pattern accounts for the whole input.
With re.MULTILINE, ^ and $ also recognize the start and end of each line:
text = "alpha one\nbeta two"
print(re.findall(r"^\w+", text, flags=re.MULTILINE))
# ['alpha', 'beta']
Without the flag, the same call returns only ['alpha']. \A and \Z remain string-edge anchors even in multiline mode.
A word boundary follows the word class
\b matches where a word character meets a non-word character or the edge of the string. Write it in a raw string so Python does not turn it into a backspace. \B tests a position with no word boundary.
re.findall(r"\bcat\b", "cat concat cat's cats") finds two copies of "cat". One is the standalone word; the other comes before the apostrophe in "cat's". The apostrophe is non-word text. The "cat" inside "concat" and the beginning of "cats" have no boundary at both ends.
This is a rule about \w, not a language-aware definition of a word. An underscore counts as a word character, so boundaries around an identifier can differ from boundaries around words in ordinary prose.
Keep alternatives inside their shared structure
The bar | has the lowest precedence. ^cat|dog$ means either "cat" at the start or "dog" at the end. It can match part of "cat food" or "hot dog". Grouping shares the anchors: ^(?:cat|dog)$. The ?: keeps this group from storing a separate capture.
The dollar anchor still permits a final newline. For exactly "cat" or "dog", write re.fullmatch(r"cat|dog", s) or use r"\A(?:cat|dog)\Z".
Order can change the returned text
Alternatives are tried left to right. re.search(r"Jan|January", "January").group() gives 'Jan' because the first branch already leads to an overall match. Put a longer overlapping branch first, January|Jan, when that is the intended choice.
A boundary can also force the engine to reject the shorter branch: \b(?:Jan|January)\b finds "January", since there is no boundary between "n" and "u". The first successful branch wins; the engine does not compare every successful branch for length.
A caret's meaning also depends on location. In ^[^#], the first caret anchors the match, while the caret inside the class excludes "#" from the first matched character.
Key Takeaways
- Anchors and boundaries test positions and consume no text.
$can match before a final newline;\Zrequires the absolute end.re.MULTILINEchanges^and$, not the string-edge anchors.\bfollows the word-character rule, including underscores.- Group alternatives when surrounding rules must apply to every branch.
- At a given position, the first alternative that leads to an overall match wins.
2Search and extract with the re module
The pattern describes what can match; the function determines where to look and what kind of result to return. A first match, a whole-input decision, a list of fields, and an iterator of positions serve different jobs. You will read Match objects safely, predict the effect of captures on collected results, and give reusable patterns clear names. Flags then adjust case, line handling, whitespace, and character rules without hiding those choices.
2.1 Choose where the match must fit
The same pattern can answer three different questions: does it appear anywhere, does it begin here, or does it cover everything? Choosing the function is part of writing the rule.
Search anywhere, at the start, or across the whole input
re.search(p, s) finds the first match anywhere. re.match(p, s) accepts only a match beginning at index zero. re.fullmatch(p, s) requires the pattern to cover the whole string. Each returns a Match object or None.
With r"\d+" on "42 apples", both search and match find "42"; fullmatch fails because " apples" remains. On "apples 42", only search succeeds. On "42", all three succeed.
Python 3.15 added re.prefixmatch as a clearer name for the behavior of re.match. Both names work in 3.15; match also works on older supported versions. The examples here use match where compatibility matters.
A flag does not move match's starting position
re.MULTILINE changes the meanings of ^ and $. It does not turn match into a scan across line starts:
import re
text = "ready\nbusy"
print(re.match(r"b", text, flags=re.MULTILINE)) # None
m = re.search(r"^b", text, flags=re.MULTILINE)
print(m.group()) # b
The search can inspect the start of the second line. The prefix match remains tied to the start of the entire string, which is "r".
Handle the no-match path first
A failed match is None, which has no .group() method. Keep the check and the use together:
text = "Room 101, floor 3"
m = re.search(r"\d+", text)
if m:
print(m.group()) # 101
else:
print("No number found")
You can also assign inside the condition: if (m := re.search(r"\d+", text)):. This assignment-expression syntax is available from Python 3.8. It performs one search and keeps its result.
Read positions as slice boundaries
m.group(), m.group(0), and m[0] give the entire matched text. m.start() is the first matched index; m.end() is the index just after the match. m.span() combines them as a tuple.
For "Room 101, floor 3", the first digit is at index 5 and the comma is at index 8. The span is (5, 8), and text[5:8] is '101'. The end index is exclusive, just like a Python slice. A span's length is therefore end - start, here three characters.
search reports only this first match. To inspect both "101" and "3", use an all-match function.
An empty match still succeeded
m = re.match(r"\d*", "abc")
print(bool(m)) # True
print(m.group()) # prints an empty line
print(m.span()) # (0, 0)
The pattern permits zero digits, so the empty prefix fits. if m: asks whether matching succeeded; if m.group(): asks whether the matched string contains characters. These tests answer different questions. Select a nonempty pattern such as \d+ when the task requires actual digits.
Key Takeaways
searchscans anywhere,matchchecks the start, andfullmatchchecks the whole string.- Check for a Match before reading its text or positions.
- Match spans use a start-inclusive, end-exclusive pair of indices.
- An empty match is truthy even though its matched string is empty.
2.2 Collect matches without losing their structure
Use findall when you want extracted strings and finditer when each result needs positions or Match methods. Both scan left to right and return non-overlapping matches.
Choose the result you need
re.findall(p, text) builds a list. If nothing matches, the result is [], so len(...) gives a match count without a separate None check. With no capturing groups, each item is the whole matched string.
import re
text = "width=20 height=10"
print(re.findall(r"\w+=\d+", text))
# ['width=20', 'height=10']
Parentheses can change that result. With one capturing group, findall returns that group's text. With two or more, it returns tuples of group texts:
print(re.findall(r"\w+=(\d+)", text))
# ['20', '10']
print(re.findall(r"(\w+)=(\d+)", text))
# [('width', '20'), ('height', '10')]
The matched regions have not changed. The result's shape has, because captures select the fields to return.
Group structure without requesting a field
A non-capturing group, (?:...), groups alternatives or repeated pieces without adding an extracted field. re.findall(r"(cat|dog)s", "cats and dogs") gives ['cat', 'dog']; re.findall(r"(?:cat|dog)s", "cats and dogs") gives ['cats', 'dogs'].
Before adding parentheses, decide whether you need their text saved. Structural grouping alone should not unexpectedly turn a list of whole matches into a list of fragments or tuples.
Keep positions with finditer
finditer returns an iterator of Match objects. Process each result in a loop:
for m in re.finditer(r"\d+", "a1 b22 c333"):
print(m.group(), m.span())
# 1 (1, 2)
# 22 (4, 6)
# 333 (8, 11)
This supports highlighting text, reporting its location, or using named captures. It also produces results one at a time instead of building a complete list of matches first, which is useful for text containing many matches.
Make extraction match the data
\w+ is convenient for word-like pieces, but apostrophes and hyphens split them. On "It's a well-known fact.", it gives ['It', 's', 'a', 'well', 'known', 'fact']. [\w'-]+ instead keeps "It's" and "well-known" together. This added class accepts apostrophes and hyphens anywhere in a run, so use it for the intended text shape.
A useful address-extraction pattern is [\w.+-]+@[\w-]+(?:\.[\w-]+)+. The repeated domain piece requires a period followed by text, so a sentence-ending period is left out. An extractor finds likely values in prose; a complete address validator asks a different question.
Convert numeric results before calculation
Matches are strings even when every character is a digit:
amounts = re.findall(r"\d+", "3 apples, 12 pears and 7 plums")
print(sum(int(n) for n in amounts)) # 22
For a decimal part, \d+(?:\.\d+)? accepts both "72" and "72.5" without adding a capture. Using \d+ alone on a decimal would extract two separate digit runs and lose the decimal point's meaning.
Key Takeaways
findallreturns a list, including an empty list when nothing matches.- Capturing-group count determines whether
findallreturns matches, strings from one group, or tuples. - Use
(?:...)for structure that should not become an extracted field. finditerkeeps each match as an object with groups and positions.- Choose word and number patterns for the actual separators in the data.
- Convert extracted numeric strings before doing arithmetic.
2.3 Reuse readable patterns and choose flags
Compiled patterns give a repeated rule a name. Flags change specific matching behavior, so keep each flag close to the pattern that needs it.
Give the rule one clear home
import re
DATE = re.compile(r"\d{4}-\d{2}-\d{2}")
m = DATE.search("Due 2026-03-15")
if m:
print(m.group()) # 2026-03-15
A Pattern object offers methods such as .search, .fullmatch, .findall, .finditer, .sub, and .split. Omit the pattern argument when calling them. Pattern methods also provide options such as pos and endpos to control a search region.
The module caches recently used patterns, so repeated module calls do not necessarily recompile. Explicit compilation mainly makes a shared rule easy to name, reuse, and change in one place.
Change only the behavior you intend
re.IGNORECASE(re.I) enables case-insensitive matching, including Unicode case pairs such as "ü" and "Ü".re.MULTILINE(re.M) makes^and$recognize each line's edges.re.DOTALL(re.S) lets.consume newlines.re.ASCII(re.A) restricts shorthand classes and word boundaries to ASCII behavior.re.VERBOSE(re.X) lets a pattern contain layout whitespace and comments.
Combine flags with |, for example flags=re.I | re.M. Multiline and dot-all solve different problems: recognizing line starts does not make the dot cross newlines.
Pass options by keyword
In re.sub, the fourth positional argument is count, not flags. Passing re.I there treats its integer value, 2, as a replacement limit. For re.sub(r"a", "o", "Anna has a banana", re.I), only two lowercase matches are changed: 'Anno hos a banana'.
With flags=re.I, every case-insensitive match is replaced and the result is 'onno hos o bonono'. Since Python 3.13, positional count and flags in sub and subn, and positional maxsplit and flags in split, are deprecated. Use keyword arguments. Module functions such as search and findall still accept positional flags.
Use layout without changing the intended characters
PHONE = re.compile(r"""
(\d{3}) # first part
[-.\s]? # optional separator
(\d{4}) # second part
""", flags=re.VERBOSE)
print(PHONE.search("call 555 0199").groups())
# ('555', '0199')
In verbose mode, ordinary pattern whitespace is ignored and an unescaped # outside a class begins a comment. A required literal space needs [ ] or \ . \s accepts any whitespace, including a tab or newline, so it is a wider rule.
A global inline flag such as (?i) belongs at the very start of the pattern in Python 3.11 and later. A scoped flag, (?i:p)ython, changes case behavior only within that group: it matches "Python" and "python", but not "PYTHON".
Read a pattern error at its reported position
An unclosed group such as r"(abc" fails during compilation. Python 3.13 and later call this exception re.PatternError; the older name re.error still works. The message points to the unpaired opening parenthesis. Fix the pattern itself before debugging the text being searched.
Key Takeaways
- Compile shared patterns for clear names and one place to maintain them.
- Choose flags by their specific effects; combine them with
|. - Use keyword
flags,count, andmaxsplitto keep arguments clear. - In verbose mode, mark literal spaces explicitly and protect literal
#characters. - Global inline flags belong at the start; scoped flags apply only inside their group.
- Pattern errors occur during compilation and identify a problem in the pattern.
3Capture parts of a match with groups
Groups turn matching text into fields your program can use. Begin with numbered and named captures, then separate stored data from structural grouping and context tests. These distinctions matter when the same pattern both recognizes a line and extracts its parts. A log-parsing loop brings them together: each accepted line becomes a record, rejected lines remain visible, and converted fields support counts and other calculations.
3.1 Name and read captured fields
A capturing group remembers the text matched by part of a pattern. Groups let you extract fields from a larger match and apply repetition or alternatives to a whole piece.
Number groups by their opening parentheses
Group 0 is the whole match. Other groups are numbered from 1 in the order their opening parentheses appear, including nested and named groups.
import re
m = re.search(r"((\d+)-(\d+))", "range 10-20")
print(m.group(0)) # 10-20
print(m.group(1)) # 10-20
print(m.group(2)) # 10
print(m.group(3)) # 20
The outer group starts first and captures the whole range; the two inner groups capture its endpoints. Escaped literal parentheses \( and structural groups (?:...) do not take capture numbers.
For a date pattern (\d{4})-(\d{2})-(\d{2}), .group(1) reads the year. .group(2, 3) returns a tuple containing month and day, while .groups() returns every capture and leaves out group 0.
Use names when the fields have roles
DATE = re.compile(
r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})"
)
m = DATE.search("Due: 2026-03-15")
if m:
print(m["year"]) # 2026
print(m.groupdict())
# {'year': '2026', 'month': '03', 'day': '15'}
(?P<name>...) defines a named capture. m["year"] and m.group("year") read the same field. Named groups also keep their numeric positions, so .group(1) still reads the year here. A name makes later code less dependent on counting parentheses correctly.
Distinguish absent captures from empty text
In (\d+)(?:\.(\d+))?, the decimal part is optional. On "42", .groups() returns ('42', None). The second capture never participated; it is not the string "0" or an empty string. .groups(default="0") can supply the fallback, giving ('42', '0').
In contrast, a group that participates with a zero-length match holds ''. Check whether the capture was absent before trying to convert or process it.
Put the quantifier in the right place
A repeated capture remembers only its last repetition. re.fullmatch(r"(\d)+", "123").group(1) returns '3': the group matched "1", then "2", then "3", and its stored value was replaced each time.
With (\d+), the group surrounds the whole digit run, so it captures '123'. Use findall or finditer when each repeated occurrence needs its own result.
Convert fields according to their meaning
m = re.search(
r"(?P<value>\d+(?:\.\d+)?)\s*(?P<unit>kg|g)\b",
"Weight: 72.5 kg"
)
if m:
record = m.groupdict()
value = float(record["value"])
print(value, record["unit"]) # 72.5 kg
The search returns a Match object. Its .groupdict() method creates the dictionary, whose values are strings. Keeping the numeric value and its unit separate lets later code calculate with the number while preserving whether it represents kilograms or grams.
Key Takeaways
- Group 0 is the full match; captures are numbered by opening-parenthesis order.
- Named captures support readable field access and
groupdict(). - An optional capture that did not participate holds
None. - A repeated capture retains its last repetition; surrounding the repeated run captures it all.
- Captured numeric text still needs conversion before calculation.
3.2 Match repeated text and test nearby context
Some groups organize a pattern, some remember text, and some inspect context without consuming it. Select the group form based on the job it needs to do.
Keep structural groups out of the result
A non-capturing group (?:...) applies a quantifier or alternative without storing a field. For a repeated domain ending, (?:\.[\w-]+)+ groups the period and following text as one repeatable piece. It adds no capture number and does not change findall into a list of those suffixes.
Require the same captured text
A backreference repeats what an earlier capture actually matched. (\d)\1 accepts "77", but not "78". (\d)\d accepts both, since the second digit is checked independently. A numbered reference uses \1; a named reference inside the pattern uses (?P=name).
import re
m = re.search(r"\b(\w+)\s+\1\b", "This is is a test")
print(m.group()) # is is
The first group captures "is"; the reference requires that same word again after whitespace. The final word boundary stops a partial second word, such as matching "the the" inside "the theory". Add flags=re.IGNORECASE when case differences should be accepted, as in "The the".
Look ahead without including the following text
A positive lookahead (?=...) requires following text; a negative lookahead (?!...) forbids it. Neither consumes what it checks.
text = "5 kg, 7 km, 12 kg"
print(re.findall(r"\d+(?= kg)", text))
# ['5', '12']
print(re.findall(r"\b\d+\b(?! kg)", text))
# ['7']
The first pattern extracts digits only. The space and "kg" are required context outside each match. The second uses a word boundary after the digits so the engine cannot accept a shorter prefix of a number merely to satisfy the negative test.
Look behind a match
(?<=...) requires preceding text, and (?<!...) forbids it. (?<=#)\w+ extracts "python" and "regex" from "Learn #python and #regex" without including either hash sign.
Python lookbehind must have a fixed width. (?<=abc) and (?<=a|b) work, but (?<=ab|c) and (?<=a+) fail during compilation. For a variable prefix, capture the wanted text after consuming the prefix. For example, #(\w+) with findall also returns the tag names.
Check several conditions at one position
RULE = re.compile(r"(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}")
print(bool(RULE.fullmatch("Secret123"))) # True
print(bool(RULE.fullmatch("secret123"))) # False
Each initial lookahead checks a condition from the same starting position: a digit, a lowercase ASCII letter, and an uppercase ASCII letter. The final .{8,} consumes the string and enforces its minimum length. Separate checks in Python code are often easier to maintain and allow a specific message for each failed condition.
Key Takeaways
- Non-capturing groups organize a pattern without adding result fields.
- A backreference repeats captured text, not just the earlier character rule.
- Lookahead checks following context without consuming it.
- Lookbehind checks preceding context and must have fixed width in Python.
- Lookarounds can test several conditions at the same position.
- Check a full value before excluding nearby context; an unconstrained shorter match can pass accidentally.
3.3 Parse text lines into records you can count
A regex can turn a consistently shaped line into named fields. A useful parser also records failures, preserves field meaning, and converts values before calculating with them.
Describe one complete record
Suppose log lines look like "2026-03-15 14:02:07 ERROR [db] Connection lost". The spaces separate the date, time, level, source, and message. Give those fields names:
import re
LOG = re.compile(
r"(?P<date>\d{4}-\d{2}-\d{2}) (?P<time>\d{2}:\d{2}:\d{2}) "
r"(?P<level>[A-Z]+) \[(?P<source>\w+)\] (?P<message>.*)"
)
The adjacent string literals become one pattern. \[ and \] require the literal square brackets around the source. Without those escapes, square brackets would define a class. The final .* permits an empty message and stops before a newline.
Read a line and handle both outcomes
records, rejected = [], []
with open("app.log", encoding="utf-8") as f:
for number, line in enumerate(f, start=1):
m = LOG.fullmatch(line.rstrip("\n"))
if m:
records.append(m.groupdict())
else:
rejected.append((number, line))
Reading one line at a time avoids loading the whole file. An explicit encoding makes the intended decoding clear. Each line usually retains its final newline, so rstrip("\n") removes that record terminator before the whole-line test. It leaves ordinary trailing spaces in the message intact.
fullmatch requires every character of the remaining line to fit the record. A search could accept a correct-looking fragment inside a damaged line and hide the problem. Rejected entries keep their line numbers and original text for inspection.
Inspect the extracted fields
The example produces:
{
'date': '2026-03-15',
'time': '14:02:07',
'level': 'ERROR',
'source': 'db',
'message': 'Connection lost'
}
Every value is a string. Named captures make the record usable without relying on positional indices. If the format changes, an increase in rejected lines gives you a visible signal instead of silently losing fields or crashing on .groupdict() after a failed match.
Summarize and validate the extracted data
from collections import Counter
counts = Counter(record["level"] for record in records)
print(counts)
print(len(rejected))
For two "ERROR" records, one "INFO" record, and one damaged line, the counts are Counter({'ERROR': 2, 'INFO': 1}) and the rejected count is 1. The damaged line contributes to neither level count.
Convert numeric fields with int or float. To check the timestamp's meaning, use datetime.strptime(record["date"] + " " + record["time"], "%Y-%m-%d %H:%M:%S") after importing datetime from datetime. A date-shaped field alone can still name an impossible day.
Use the parser for the data format
A comma can occur inside a quoted CSV field such as "Lima, Peru", and JSON values can nest. Use csv or json for those formats. A line-oriented regex is a good fit when the line itself has a short, known structure, such as this log record.
Key Takeaways
- Compile a whole-record pattern with a name for each useful field.
- Remove the line terminator before applying a whole-line match.
- Record failed lines with enough information to inspect them.
groupdict()produces string-valued fields; convert values when their meaning requires it.- Count records only after they have been parsed successfully.
- Use the standard format parsers for CSV and JSON.
4Validate input with regular expressions
A validator translates an input policy into checks the program can explain. Some rules concern the written shape, such as separators and field lengths. Others concern meaning, such as a real date or an integer within a range. You will build a complete-string format check, test its boundaries, and combine it with the appropriate parser or comparison. Normalization choices and input limits belong to this design from the start.
4.1 Turn a format rule into a whole-input check
Validation asks whether the entire input follows an agreed rule. First decide which characters and variants are allowed, then translate those requirements into a pattern.
Require the whole string
re.search(r"\d{4}", "abc12345") finds four digits inside the text. It says nothing about the extra characters. Use re.fullmatch when every character must fit.
The anchors ^ and $ can also surprise you: re.search(r"^\d{4}$", "2024\n") succeeds before the final newline. re.fullmatch(r"\d{4}", "2024\n") fails. Absolute string anchors \A and \Z give the strict edge behavior, but fullmatch states the whole-input intention directly.
Count each part of a rule
A username has 3 through 16 characters, begins with an ASCII letter, and continues with ASCII letters, digits, or underscores:
import re
USERNAME = re.compile(r"[A-Za-z][A-Za-z0-9_]{2,15}")
print(bool(USERNAME.fullmatch("ana_99"))) # True
print(bool(USERNAME.fullmatch("a1"))) # False
The first class supplies one required character. The repeated class supplies 2 through 15 more, giving total lengths of 3 through 16. Repeating it {3,16} would shift both total limits by one. "9lives" fails the first-character rule, and "ana-99" fails the allowed-character rule.
Encode ranges when they remain readable
A 24-hour time uses (?:[01]\d|2[0-3]):[0-5]\d. The hour is either 00 through 19 or 20 through 23; the minute is 00 through 59. With fullmatch, "09:30" and "23:59" pass, while "24:00", "9:30", and "19:60" fail.
A six-digit hex color uses #[0-9A-Fa-f]{6}. A date shape uses \d{4}-\d{2}-\d{2}. The date pattern controls the field widths and separators; checking the calendar is a separate step.
Normalize the variants the interface accepts
Postal-code shapes differ. Examples include a US ZIP shape \d{5}(?:-\d{4})?, a Dutch shape [1-9][0-9]{3} ?[A-Z]{2}, and a Canadian shape [A-Z]\d[A-Z] ?\d[A-Z]\d. A shape match can still describe an unused code; confirming assignment needs real code data.
If surrounding whitespace and case are harmless for a code, apply .strip().upper() first. The input " 1012 ab " then becomes "1012 AB". The optional literal space in the pattern accepts zero or one space, not arbitrary whitespace.
Choose digits deliberately. \d accepts Unicode decimal digits, including fullwidth ones. Use [0-9] or flags=re.ASCII when the required format is ASCII.
Test both sides of every boundary
Build a small table of accepted and rejected inputs:
cases = [("abc", True), ("a1", False), ("9ab", False),
("a" * 16, True), ("a" * 17, False),
("", False), ("abc\n", False)]
for value, expected in cases:
assert bool(USERNAME.fullmatch(value)) == expected
Also test separators and preprocessing choices. If you trim input before matching, test the complete validator as well as the bare pattern. An input loop can keep asking after a failure and explain the expected form with a concrete example.
Key Takeaways
- Use
fullmatchwhen every character must meet the format rule. - Count fixed characters as part of the total length.
- Normalize accepted case and spacing differences before matching.
- Choose Unicode or ASCII digit behavior explicitly.
- Test empty input, boundaries, separators, and trailing newlines.
4.2 Check meaning, ranges, and input limits
A format check can accept a string whose value is impossible or unsuitable. Combine short pattern checks with Python code that understands the value and the application's rules.
Separate a date's shape from its calendar meaning
import re
from datetime import date
def read_date(text):
if not re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}", text):
return None
try:
return date.fromisoformat(text)
except ValueError:
return None
The pattern requires the written form YYYY-MM-DD. The parser checks whether the date exists. "2026-02-30" has the right shape but the parser rejects it. These checks also let an interface distinguish a format error from an impossible date.
Put arithmetic ranges in code
A value from 0 through 255 with no leading zeros needs two rules: a permitted spelling and an in-range integer. 0|[1-9][0-9]{0,2} describes the spelling. Then compare the converted value:
def valid_byte(text):
return (re.fullmatch(r"0|[1-9][0-9]{0,2}", text) is not None
and 0 <= int(text) <= 255)
"0" and "255" pass; "007" fails the spelling rule; "256" fails the range rule. A loose \d{1,3} check would admit the leading zeros. A giant range pattern can encode 0 through 255, but the split check is easier to read. For full IP addresses, use ipaddress.
Match the real purpose of the check
A loose email pattern such as [^@\s]+@[^@\s]+\.[^@\s]+ catches common typing errors, including spaces or a missing domain ending. It accepts an address such as "ana+news@example.museum". Complete email grammar is more complex; mailbox access is checked by sending a link or code and having the user complete verification.
Phone input often needs normalization of spaces, hyphens, periods, and parentheses. Keeping digits and a plus sign can give "+442079460958" from "+44 20 7946 0958". Follow that cleaning step with a structure and length check: simply deleting other characters could leave multiple plus signs. An international E.164 number has at most 15 digits; a length check alone cannot confirm that a number is assigned.
Keep checks readable and bounded
An allowlist states what is accepted. It is easier to reason about than a blocklist trying to enumerate every forbidden character. Separate length, character-type, and content checks can produce useful messages such as "Use at least one digit."
Check the maximum length of untrusted input before running a pattern. Avoid ambiguous nested repetition such as (\w+\s?)+: a nearly matching long string can cause excessive backtracking and stall a service. A clear, bounded rule makes both the accepted input and the amount of work easier to control.
A validated value still needs the right handling at its destination. Use parameterized SQL queries, HTML escaping, and shell argument lists when building those outputs. Format validation answers whether input fits a rule; output handling controls how another system interprets it.
Key Takeaways
- Use a date parser to check calendar meaning after checking the written form.
- Combine a spelling rule with numeric conversion and range tests.
- Check mailbox access with completed verification, and phone structure after cleaning.
- Prefer allowlists and small checks that support specific error messages.
- Bound untrusted input before matching and avoid ambiguous repetition.
- Use destination-specific output handling even after a format check succeeds.
5Transform and clean messy text
Text transformation needs a clear purpose: a display value, a structured record, or a comparison key. You will replace matches with fixed text, captured fields, or computed values, then split varying separators. A cleaning function puts selected changes in a deliberate order and protects meaningful data. Unicode normalization completes that process by handling equivalent stored spellings while keeping stronger search-key changes separate from display text.
5.1 Replace matches and split varying separators
Substitution transforms matched text, while regex splitting uses a pattern to locate separators. Both return new values; they do not modify a string in place.
Replace fixed matches or reuse captured text
import re
text = "too many\tspaces"
text = re.sub(r"\s+", " ", text)
print(text) # too many spaces
re.sub(pattern, replacement, text) replaces every non-overlapping match by default. Assign its result to keep the change. count=1 limits it to the first replacement; count=0 means no limit.
A replacement template can refer to captures. \g<1> reads a numbered group, \g<name> reads a named group, and \g<0> reads the whole match:
result = re.sub(r"(\d{2})/(\d{2})/(\d{4})",
r"\g<3>-\g<2>-\g<1>", "15/03/2026")
print(result) # 2026-03-15
The input is day/month/year. Each field is captured once, then inserted in year-month-day order. This changes its written form; it does not test whether the date exists.
Make group references unambiguous
Write replacement templates as raw strings. In an ordinary literal, "\1" is a control character, not a group reference. Raw r"\1" preserves the intended reference.
Use the explicit \g<...> form when another digit follows. r"\g<1>0" inserts group 1 followed by a literal zero. r"\10" asks for group 10 and fails if there is no such group. A literal backslash in a replacement template uses r"\\".
Pattern syntax and replacement syntax differ. In a pattern a named backreference is (?P=name); in a replacement it is \g<name>. re.escape prepares literal text for a pattern, not for a replacement template.
Compute a replacement from the match
result = re.sub(r"\d+", lambda m: str(int(m.group()) * 2),
"3 eggs, 250 g flour")
print(result) # 6 eggs, 500 g flour
The function receives one Match object at a time and must return text. It converts each numeric string, doubles its value, then converts the result back to a string. Function results are inserted literally, which also makes a function useful for inserting supplied text containing backslashes.
re.subn returns both the transformed string and the replacement count. re.subn(r"\s+", " ", "a b c") yields ('a b c', 2). Pass count and flags by keyword; positional use in these functions is deprecated from Python 3.13.
Split on a separator rule
print(re.split(r"[,;]\s*", "red, green;blue; yellow"))
# ['red', 'green', 'blue', 'yellow']
The separator is a comma or semicolon plus any following whitespace. maxsplit limits the number of splits; its default, zero, leaves them unlimited. Pass it by keyword.
Capturing the separator keeps it in the result: re.split(r"([+-])", "3+4-2") returns ['3', '+', '4', '-', '2']. A non-capturing version drops those operators. A separator at the start or end can produce an empty field, which may be meaningful data; do not discard it without deciding what it represents.
Key Takeaways
- Assign the new string returned by
sub. - Use raw replacement templates and
\g<...>for clear group references. - A replacement function receives a Match and returns literal replacement text.
subnreturns the new text and the replacement count.splitcan recognize variable separators; captured separators stay in the list.- Pass
count,flags, andmaxsplitby keyword.
5.2 Build a cleaning function that preserves useful data
Cleaning gives inconsistent text an agreed form for display, storage, or comparison. Choose that form before deleting or replacing anything, and keep the original text when later work may need it.
Trim edges without changing the middle
s.strip() removes whitespace at both ends. lstrip and rstrip work on one end. With an argument, these methods treat the argument as a set of removable characters, not as a prefix or suffix.
"www.wiki.org".strip("w.") yields 'iki.org': it keeps removing any "w" or "." at the edge, including the first "w" of "wiki". For one exact prefix, "www.wiki.org".removeprefix("www.") yields 'wiki.org'. removeprefix and removesuffix are available from Python 3.9.
Decide which whitespace carries structure
" ".join(s.split()) collapses runs of whitespace and trims the ends. So does re.sub(r"\s+", " ", s).strip(). Spaces, tabs, newlines, and non-breaking spaces all become ordinary spaces.
For a single text field this can be useful. If newlines separate records, process the records first or preserve line breaks explicitly. A cleaning rule should follow the information you need to keep.
For caseless comparisons, make a casefold() key. It is stronger than lower(): "Straße" becomes "strasse", which agrees with casefolded "STRASSE". Keep the display form separately so a comparison rule does not erase a person's chosen spelling.
Replace selected characters in one pass
import re
import unicodedata
QUOTES = str.maketrans({"“": '"', "”": '"', "’": "'"})
def clean(text):
text = unicodedata.normalize("NFC", text)
text = text.translate(QUOTES)
return re.sub(r"\s+", " ", text).strip()
str.maketrans creates a translation table; translate applies it to individual characters. Here, curly quotation marks become straight ones. Normalization comes first so equivalent Unicode spellings reach later steps in the same form.
A deletion table built from string.punctuation removes ASCII punctuation only. Curly quotation marks and guillemets remain. A regex such as [^\w\s] removes anything that is neither a word character nor whitespace, including those quotation marks, but keeps underscores because _ belongs to \w.
Protect values before removing punctuation
Deleting or spacing punctuation can corrupt data. Changing "Price 3.5 kg" to "Price 3 5 kg" turns one decimal value into two digit runs. Extract or standardize required numbers, dates, and codes before a broad punctuation step, or write a narrower rule that preserves their separators.
The order also affects word separation. Deleting a hyphen can join two pieces into one; replacing it with a space preserves a break. Decide which result fits the field's purpose before writing the transformation.
For real HTML, use html.parser or an HTML library. A simple <[^>]+> pattern can remove tags in a known short snippet, but attributes, comments, and scripts can contain syntax it cannot handle. Decode entities such as "&" with html.unescape.
Test the complete pipeline
raw = " “Cafe\u0301”\t menu\n "
assert clean(raw) == '"Café" menu'
This checks Unicode composition, quote conversion, whitespace collapse, and trimming together. Add cases with already-clean text and with values the function must preserve. Keep each step's order explicit in the function so a later edit does not silently change how the rules interact.
Key Takeaways
- Define the target form and retain raw text when it is needed later.
strip(chars)removes edge characters;removeprefixremoves an exact prefix.- Whitespace collapse can remove line structure, so apply it at the right level.
- Use translation tables for selected character changes and regex for character categories.
- Protect decimal values and other meaningful separators before broad cleanup.
- Test the complete function, including the order of its operations.
5.3 Normalize equivalent Unicode spellings
A Python string is a sequence of Unicode code points. A visible character can use more than one code point, so text that looks identical can compare unequal and behave differently in a regex.
Inspect what the string stores
The character "é" can be U+00E9 or the sequence U+0065 followed by U+0301, a combining acute accent. Thus "caf\u00e9" == "cafe\u0301" is False. Their lengths are 4 and 5 because len counts code points, not visible characters.
import re
import unicodedata
a = "caf\u00e9"
b = "cafe\u0301"
print(unicodedata.normalize("NFC", a) ==
unicodedata.normalize("NFC", b)) # True
Normalize both inputs to the same form before comparison. unicodedata.is_normalized("NFC", text) tests whether conversion is needed without changing the string.
Choose canonical composition or decomposition
NFC composes canonically equivalent sequences where a precomposed form exists. NFD decomposes them into base characters and combining marks.
Normalization also matters before matching. A combining accent is not a \w character. re.findall(r"\w+", "cafe\u0301 au lait") gives ['cafe', 'au', 'lait'], leaving the accent outside the match. Applying NFC first gives ['café', 'au', 'lait'].
Use compatibility forms for the intended key
NFKC applies compatibility mappings and then composition; NFKD applies compatibility mappings and decomposition. They turn the ligature "fi" into "fi", fullwidth "2024" into "2024", and "Ⅻ" into "XII". NFC preserves these distinctions.
Compatibility changes can remove meaning: "x²" becomes "x2". Use compatibility forms for search keys and identifiers whose policy accepts those mappings, and retain original or NFC text for display. None of the four forms merges Latin "a" with the similar-looking Cyrillic "а"; visual similarity is different from Unicode equivalence.
Make accent-insensitive keys separately
def accent_key(text):
decomposed = unicodedata.normalize("NFD", text)
return "".join(c for c in decomposed
if not unicodedata.combining(c))
This drops characters with a nonzero canonical combining class. It turns "Crème brûlée" into "Creme brulee". It is not a general transliteration: "ø" stays "ø", and "Łódź" becomes "Łodz" because "Ł" does not decompose into a base letter plus an accent.
Removing accents can merge different words. Use such keys for loose matching while preserving accented text for display and storage.
Combine normalization with case folding
A common loose search key is unicodedata.normalize("NFKC", text).casefold(). For strict Unicode caseless comparison, normalize again after folding, since folding can return unnormalized text for a few characters:
def caseless_key(text):
nfd = lambda s: unicodedata.normalize("NFD", s)
return nfd(nfd(text).casefold())
Normalization cannot repair incorrect decoding: "Café" needs the original bytes decoded with the right encoding, such as open(path, encoding="utf-8").
Key Takeaways
- Python
lencounts code points, which can differ from the number of visible characters. - NFC composes canonical equivalents; NFD decomposes them.
- Normalize before regex matching when combining marks affect the accepted characters.
- NFKC and NFKD apply compatibility mappings that can remove meaningful distinctions.
- Accent removal is a separate key-building step and does not transliterate every letter.
- For strict caseless comparison, normalize, casefold, and normalize again.
- Correct decoding comes before normalization.
Python Regular Expressions examples
1Build a pattern you can read
18 steps
- 1IntroductionDescribe what can vary
A text field can vary without being unpredictable. A label may begin with a letter, contain digits, and use a fixed separator. A regex describes those choices in a short rule.
You will build the rule from characters, repetitions, and positions. At each stage, distinguish what the pattern consumes from what it merely checks. That distinction explains why a pattern can find a useful fragment yet still fail as a validator.
- 2ExplanationLet Python pass the pattern through
Python reads the string literal before the regex engine sees the pattern. Use a raw literal so its backslashes survive that first step.
import re m = re.search(r"\bfox\b", "A fox waits") if m: print(m.group()) # foxIn an ordinary literal,
"\b"becomes a backspace. Raw syntax passes\bto the engine as a word-boundary test; it does not make regex operators literal. - 3TipProtect punctuation that belongs to the text
The dot in
r"2.6"can accept "x", so that pattern also fits "2x6".r"2\.6"requires a period.For a supplied label such as "C++", use
re.escape(label)before inserting it into a regex. It protects the metacharacters in that value. If you only need to check for the exact label anywhere in text,label in textexpresses the task directly without building a pattern. - 4ChallengeFind a supplied version label
A variable
labelcontains "r4.2+". You must locate that exact text inside a longer note. How can you do it with a regex while keeping the punctuation literal?---reveal---
Use
re.search(re.escape(label), note)and check the result before reading it. Escaping protects both the period and plus sign. Merely writing a raw string would preserve escapes but leave these characters active as regex operators. - 5ExampleRead two character positions
Consider
[A-Z][0-9]on the text "R58 s9 T4".[A-Z]requires one uppercase ASCII letter.[0-9]requires one ASCII digit immediately after it.
findallreturns['R5', 'T4']. "R58" contributes only its first two characters, and lowercase "s" does not satisfy the first class. A class supplies one position, even when the surrounding text contains a longer run. - 6ExplanationChoose the accepted character set
\daccepts Unicode decimal digits,\waccepts Unicode alphanumeric characters plus_, and\saccepts whitespace. Capital forms such as\Dinvert those sets.Thus
\w+keeps "café" together and also accepts "½".[a-z]+stops before "é". Use[0-9]orre.ASCIIwhen a digit field requires ASCII. A dot is wider than a class, but it still excludes newlines unlessre.DOTALLis enabled. - 7ChallengeRestrict a machine code to ASCII
A code contains one uppercase ASCII letter and one ASCII digit. It must reject "Q٣". What two-position pattern describes its characters?
---reveal---
Use
[A-Z][0-9]. The explicit digit range excludes the Arabic-Indic digit.[A-Z]\dwould accept it under default Unicode matching. These are character rules; applying them withfullmatchwould also require the complete input to be exactly two characters. - 8ExplanationCount repeats of the preceding item
A quantifier repeats the item immediately before it.
[0-9]+requires a digit run;[0-9]*also accepts no digits.[0-9]{2,4}accepts two through four digits in each match.For a repeated pair, group it:
(xy)+accepts "xyxy".xy+repeats only "y" and accepts "xyyy". Count fixed pieces too: one initial letter plus{2,5}following characters gives a total length of three through six. - 9ExampleWatch a greedy delimiter match
For "note",
<.+>matches from the first "<" to the last ">". Greedy.+takes as much as it can while leaving the suffix able to match.<.+?>tries a shorter run first, sofindallgives['<i>', '</i>']. A delimiter-focused alternative,<[^>]+>, explicitly prevents the inside run from crossing a closing angle bracket. The accepted structure can often replace a broad wildcard. - 10ExampleGive a digit back to the suffix
Trace
[0-9]+0against "4800".- The greedy run first consumes all four digits.
- The final literal "0" has no text left to use.
- The engine gives back the last digit, allowing the suffix to match it.
The whole match is "4800". Greedy does not mean the run keeps every character forever; ordinary greedy repetition can backtrack so the complete pattern succeeds.
- 11TipRemove ambiguous ways to divide a run
Nested repetition such as
(a+)+bcan divide the same run of "a" characters in many ways. A missing "b" forces the engine to explore those divisions.Use a simpler rule such as
a+bwhen it expresses the same complete strings, and bound untrusted input first. Python 3.11+ also provides possessive repetition and atomic groups. Protecting the inner repetition can help; wrapping the entire failing expression leaves its internal search intact. - 12ChallengePredict the next non-overlapping match
What does
re.findall(r"[0-9]{2,3}", "5 62 83476")return?---reveal---
The result is
['62', '834', '76']. The single digit cannot match. Greedy repetition takes three digits from the long run, then the search resumes at its end and finds two more. A bound on a substring match does not make a longer run invalid as a whole. - 13ExplanationDistinguish line endings from string endings
^checks the start, and$checks the end or the position before a final newline. Withre.MULTILINE, they also recognize each line's edges.\Aand\Zstay tied to absolute string edges. Python 3.14+ also spells the absolute end as\z. On "done\n",done$can match butdone\Zcannot. These tests consume no characters, so the newline never becomes part of the match merely because$accepts its position. - 14ConnectionUse boundaries that follow the word class
\btests where a word character meets non-word text or a string edge. It follows\w, including its underscore rule.In "fox foxes fox_name fox's",
\bfox\bfinds the standalone "fox" and the piece before the apostrophe. It does not find a complete bounded "fox" before "es" or "_name". Boundaries describe character-class transitions, so they do not always match a reader's idea of a whole word. - 15ExampleKeep shared rules around both branches
^yes|no$means "yes at the start" or "no at the end". The bar splits the surrounding expression because alternation has low precedence.\A(?:yes|no)\Zputs both alternatives under the same strict edge rules.re.fullmatch(r"yes|no", text)states the same whole-input intention directly. Structural grouping prevents a rule intended for both branches from attaching to only one. - 16ChallengeExplain a shorter alternative
Why does
re.search(r"Aug|August", "August").group()return "Aug", and how could a boundary make it find "August"?---reveal---
The first alternative succeeds without needing the longer branch. With
r"\b(?:Aug|August)\b", "Aug" fails the ending boundary before "u". The engine then tries "August", whose end is a boundary, so that whole word is returned. - 17ChallengeBuild a complete two-branch code rule
A field must be "ON" followed by two ASCII digits or "OFF" followed by two ASCII digits. It cannot contain surrounding text or a final newline. Write one check for
text.---reveal---
Use
re.fullmatch(r"(?:ON|OFF)[0-9]{2}", text). The group shares the digit suffix, the class limits digits to ASCII, and the count requires exactly two.fullmatchalso rejects an otherwise correct code with extra text or a newline attached. - 18RecapRead a rule in three passes
Read a pattern's accepted characters first, its repetition next, and its position tests last. Grouping tells you which pieces share those rules.
Before using it, separate Python string syntax from regex syntax and decide whether the task asks for a substring or a complete value. That decision determines whether matching part of a longer input is useful or a bug.
2Choose a result you can use
15 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionMatch the operation to the task
- 2ExplanationAsk where the pattern must fit
- 3ExampleUse a match as a slice
- 4Key InsightEmpty text can be a successful match
- 5ChallengeReject an embedded number
- 6ExplanationPredict the list shape before using it
- 7ExampleRetain the original locations
- 8TipKeep decimal values in one match
- 9ChallengeChoose the extraction output
- 10ExplanationName a pattern you reuse
- 11ExplanationChoose flags by what changes
- 12ExampleKeep meaningful spaces in verbose mode
- 13ChallengeFind why a dot stops early
- 14ChallengeKeep whole tokens under case changes
- 15RecapKeep scope and output visible
3Extract fields from a record
16 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionGive matched pieces a useful role
- 2ExampleNumber nested captures from the outside
- 3ExplanationName the field you want to read
- 4Key InsightDistinguish a missing field from the last repeat
- 5ChallengeCapture the whole value under a name
- 6ExplanationRepeat the text that was found
- 7ExampleCheck the unit outside the match
- 8TipHandle a prefix whose width varies
- 9ChallengeExclude a unit without losing digit prefixes
- 10ExampleDescribe a complete short log line
- 11ExampleHandle success and failure in the loop
- 12TipPreserve the fields a broad trim would change
- 13ExampleSum values after conversion
- 14ChallengeKeep damaged lines out of the totals
- 15ChallengeExtract only equal-code records
- 16RecapCarry fields safely into code
4Build a validator from a written rule
13 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionDecide what acceptance means
- 2ExampleAllocate the total character count
- 3ExplanationApply the format to every character
- 4ConnectionNormalize only accepted differences
- 5ChallengeTest both length boundaries
- 6ExampleCheck whether a date exists
- 7ExampleKeep spelling and range as separate checks
- 8TipBound the input and the matching work
- 9ConnectionSeparate a usable shape from real-world verification
- 10ChallengeRepair a range check with leading zeros
- 11ChallengeValidate an agreed code policy
- 12Key InsightTest failure paths as well as accepted values
- 13RecapLet each check answer its own question
5Transform text without losing its meaning
17 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionChoose the form you want to keep
- 2ExampleReorder captured fields
- 3ExplanationCompute from each match
- 4ExampleDecide whether separators belong in the result
- 5ChallengeLimit a computed replacement
- 6TipRemove a prefix instead of a character set
- 7ExampleTranslate selected punctuation
- 8ConnectionPreserve values before broad cleanup
- 9ChallengeKeep a decimal measurement intact
- 10ExplanationInspect stored characters before matching
- 11ExplanationChoose among the four normal forms
- 12ExampleBuild a key for caseless comparison
- 13ExampleRemove decomposed accents for a loose key
- 14ChallengeExplain unequal visible spellings
- 15TipCorrect decoding before normalization
- 16ChallengePut a cleaning pipeline in order
- 17RecapSeparate display values from comparison keys
Python Regular Expressions practice questions
Set 1: Read patterns and predict results10 Practice Questions
Question 1 of 10
re.findall(r"\b([A-Za-z]+)\s+\1\b", "go go gone go") return?Show answerHide answer
findall returns only "go". The final two words do not repeat, and a second match cannot overlap the first one.Question 2 of 10
re.findall(r"(\w+):([0-9]+)", "oak:6 pine:14") return?Show answerHide answer
findall does not infer integer types or convert the extracted values automatically.Question 3 of 10
m = re.fullmatch(r"(\d)+", "846"), what is m.group(1)?Show answerHide answer
(\d+).Question 4 of 10
re.findall(r"[0-9]{2,3}", "4 83 61728") return?Show answerHide answer
Question 5 of 10
re.match(r"[0-9]+", "code 58") return?Show answerHide answer
match requires the pattern to begin at the string's start, where this input has "c", not a digit. search would find "58" later in the text. A failed single-match operation returns None; an empty list belongs to an all-match operation such as findall.Question 6 of 10
Show answerHide answer
re.escape protects the period and plus sign so the engine treats both as literal characters. A raw string preserves backslashes, but it does not remove regex meanings from punctuation. Compiling the unescaped text would keep those special meanings too.Question 7 of 10
re.findall(r"[A-Z][0-9]", "D43 e8 F2") return?Show answerHide answer
[A-Z]. A character class does not absorb a complete run of digits; that would require a quantifier after the digit class.Question 8 of 10
s?Show answerHide answer
fullmatch requires the letter and all three digits to account for the entire input. A prefix check would also accept trailing text, while search could ignore text at both ends. The count belongs only to the digit class, so {3} means three digits after the letter.Question 9 of 10
re.split(r"[;|]\s*", "lime; pear|plum") return?Show answerHide answer
\s* consumes the space after the semicolon. Separators are omitted because the pattern has no capturing group; square brackets define a class, not a capture.Question 10 of 10
re.sub(r"[^\w\s]", "", "load=6.25 kg"), then extracts all [0-9]+ runs and sums their integer values. What total results?Show answerHide answer
Set 2: Choose functions and validate formats10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
re.search(r"May|Mayday", "Mayday call").group() return?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
r"BEGIN.*END" to match across newline characters?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
m = re.search(r"[0-9]+", "bay 742 east"), what are m.span() and the length of m.group()?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
P = re.compile(r"(?P<item>[a-z]+)=(?P<n>[0-9]+)"). It receives the file line "bolts=18\n". What operation returns its two named fields after removing only the line terminator?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
m = re.fullmatch(r"(?P<whole>[0-9]+)(?:\.(?P<part>[0-9]+))?", "93"), what is m.groupdict()?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}", s), but s is "2028-04-31". What additional check rejects it for the right reason?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
s = "9 12", what does re.sub(r"([0-9]+)", r"\g<1>0", s, count=1) return, and why would r"\10" be unsuitable here?Show answerHide answer
Save this lesson to see this answer.
Set 3: Combine extraction, grouping, and cleaning10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
needle is supplied by a user. The program must find that exact text as a substring of message; no regex features are needed. What is the clearest test?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
(m+)+n. What rewrite preserves its accepted complete strings and removes the ambiguous nested repetition?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
re.findall(r"^id=[0-9]+$", "id=31\nxid=44\nid=57\n", flags=re.MULTILINE) return?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
re.VERBOSE and must accept exactly the text "A B#C", including one space and the hash sign. What pattern body meets the rule with .fullmatch()?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
re.findall(r"\b[0-9]+\b(?! kg)", "16 kg; 24 km; 8 kg") return, and why is the boundary after the digits needed?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
"INFO 7", "ERROR 12", and "INFO 4" into named fields level and n; it rejects "ERROR x". What result should a per-level sum of n and a rejection count report?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
s = "jalapen\u0303o", what happens when re.findall(r"\w+", s) runs before and after NFC normalization?Show answerHide answer
Save this lesson to see this answer.
Set 4: Diagnose whole-input and extraction bugs10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
re.findall(r"\w+", "½ café _x") return with default string-pattern flags?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
m = re.match(r"[0-9]*", s) and accepts input when m is truthy. What happens for s = "zone", and what replacement call enforces a nonempty whole field of ASCII digits?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
"warns/errors". Why does re.findall(r"(warn|error)s", text) lose the final "s", and what preserves complete tokens?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
m = re.fullmatch(r"((?P<left>[0-9]+)):(?P<right>[0-9]+)", "27:81"), what do m.group(2) and m.group("right") contain?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
(?<=ID=|KEY=)[0-9]+ fails to compile. What rewrite extracts the numeric values after either prefix from prose while avoiding the width error?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
.strip().upper() before checking r"[A-Z]{2}[0-9]{3}" with fullmatch. How does it handle " zx408\n"?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
cleaned enforces this policy?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
re.subn(r"([0-9]+)g\b", lambda m: str(int(m[1]) + 5) + "g", "8g 23g 4kg", count=1) return?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 5: Repair text-processing pipelines10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
re.search(r"^open|closed$", s) is used to accept only the complete strings "open" and "closed". It wrongly accepts "open soon" and "closed\n". What repair rejects both while keeping the two intended strings?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
re.fullmatch(r"[0-9]+?0", "5600"), and what changes if the pattern becomes [0-9]++0 in Python 3.11+?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
re.sub(r"x", "-", "XxxX", flags=re.IGNORECASE, count=2) return?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
"2.4 kg; 6 kg" using re.findall(r"[0-9]+(\.[0-9]+)?", text) and tries to sum float(x) for each result. What correction returns usable whole quantities without manual tuple handling?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
r"(?P<level>INFO|ERROR) (?P<n>[0-9]+)" with fullmatch. Its lines are "INFO 3\n", "ERROR 9\n", "bad\n", and "INFO 5". What accepted-record count and rejection count result after removing each final newline?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
re.findall(r"(?<=@)[A-Za-z]+", "@north and @south") return?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
re.search(r"[0-9]{1,2}", s) followed by int(s) <= 75. Inputs include "x25", "00", "75", and "76". What repair prevents conversion failure, rejects leading zeros, and keeps the inclusive upper endpoint?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
\w and whitespace, then applies NFC. Why can it turn "re\u0301sume\u0301" into an unaccented key, and what order preserves the accents before punctuation removal?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
unicodedata.combining(c), and casefolds. What pair of keys results for "Åland" and "Køge", and why do the two accented-looking letters behave differently?Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Aggregation
Counter reports how many accepted log records have each severity level.Allowlist
Alternation
|, trying them in order until one permits the whole pattern to match.June|Jun can return "June" before the shorter branch is attempted.Anchor
\Z rejects a match that ends before a newline still present in the input.ASCII
[0-9] keeps a code's digits restricted to the characters "0" through "9".Atomic group
(?>a+)+b removes the ambiguous divisions of that run.B
Backreference
Backtracking
[0-9]+0 return a final zero to the literal suffix.Blocklist
Boundary case
C
Canonical equivalence
Capturing group
([0-9]+) saves all digits together.Case folding
Catastrophic backtracking
(a+)+b on a long run of "a".Character class
[A-F] accepts the initial "B" in "B29" without consuming its digits.Code point
Combining mark
\w+ match before NFC composes the accented letter.Compatibility mapping
Compiled pattern
re.compile, carrying its pattern and matching flags together.TIME when several parts of a program share that format rule.E
Escaping
re.escape prevents its period from acting as a wildcard.F
findall
findall function collects non-overlapping matches in a list whose item shape depends on the pattern's capturing groups.findall gives tuples so a name and its numeric text stay paired.finditer
finditer function returns an iterator yielding a Match object for each non-overlapping match in input order.finditer to highlight numeric matches while keeping each result's original span.Fixed-width pattern
a|b works in lookbehind because both branches take one character.Flag
re.DOTALL lets a dot consume a line break between two required markers.Format
Full match
[0-9]+ fails on "73 items" because the words remain outside the digit run.G
Greedy quantifier
<.+> can span several angle-bracketed pieces in one match.Group 0
groupdict
groupdict method returns a dictionary linking every named capture to its captured string or its absent-value fallback.groupdict to turn a matched log line into fields before converting its numeric count.I
Input-length limit
L
Lazy quantifier
<.+?> stops at an earlier closing delimiter when that allows success.Line-oriented parsing
Literal character
cat, while the dot in c.t is a wildcard.Lookahead
Lookbehind
M
Match object
.group() because a failed search returns None.Match span
(3, 6) lets text[3:6] recover exactly the same three matched characters.Metacharacter
N
Named group
(?P<name>...) that supports meaningful field access as well as numeric access.m["source"] without counting parentheses.Negated class
[^,] can consume a newline because it excludes commas only.NFC
NFD
NFKC
NFKD
Non-capturing group
(?:...) without saving a field or receiving a capture number.findall(r"(?:cat|dog)s", text).Non-overlapping matches
Normalization
Numeric conversion
float lets the extracted text "9.4" contribute to a measurement total.O
Optional capture
None in the Match object.P
PatternError
PatternError is the Python 3.13+ exception for invalid regex syntax; the compatible earlier name is re.error.PatternError points to an unpaired opening parenthesis when the pattern omits its closing partner.Possessive quantifier
a++a consumes the whole "a" run and leaves nothing for its suffix.Precedence
^up|down$ apply a different anchor to each branch.Prefix match
[0-9]+ can accept "73" at the beginning of "73 items".Preprocessing
.strip().upper() can make accepted variants consistent.Q
Quantifier
{2,5} repeats the digit class in [0-9]{2,5} two through five times.R
Range
[0-9] accepts ASCII digits, so a fullwidth digit does not satisfy that class.Raw string
r"\bfox\b" passes the boundary escapes to the regex engine.Record
ReDoS
Regex splitting
Regular expression
[0-9]+ finds a digit run even when its length changes between messages.Rejected line
Replacement function
Replacement template
sub that can insert captured text through references such as \g<name>.S
Scoped flag
(?i:p)ython allows an uppercase first letter but preserves the suffix's case.Semantic validation
Shorthand class
\d, \w, or \s that names a commonly used character set in a pattern.\s can match a non-breaking space as well as an ordinary space.subn
subn function performs regex substitution and returns a tuple containing the new text and the number of replacements made.subn shows how many whitespace runs were replaced in a cleaning pass.Substitution
T
Text cleaning
Translation table
str.translate.V
Validation
fullmatch rejects a correct-looking code embedded in extra unwanted text.Verbose mode
[ ] keeps a required space that ordinary layout whitespace would lose.W
Whitespace collapse
Word boundary
Word character
\w is broader than an ASCII letter range.Z
Zero-width assertion
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.