Python Regular Expressions

Text Processing and Regular Expressions in Python

Learn to search, extract, validate and clean text in Python. You write regular expression patterns with character classes, quantifiers, anchors and groups, and use the 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

  1. 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 string
      Recognize 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 classes
      Use 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 quantifiers
      Use 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 alternatives
      Tie a match to the start or end of a string, a line or a word, and write alternatives with the right precedence and order.
  2. 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 objects
      Pick 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 finditer
      Collect 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 flags
      Store reusable patterns as compiled Pattern objects, change matching with flags passed safely by keyword, write readable verbose patterns, and read pattern errors.
  3. 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 groups
      Mark 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 match
      Use non-capturing groups, backreferences and lookahead or lookbehind assertions to express conditions that a plain sequence cannot.
    • Turn lines of text into structured records
      Read 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.
  4. 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 format
      Use 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 limits
      Recognize what a pattern cannot check, add code for dates, ranges and lengths, accept reasonable variants, and keep validation readable and safe.
  5. 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.split
      Substitute 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 expressions
      Decide 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 matching
      Explain why identical-looking strings can differ, apply the four normalization forms with unicodedata, and build accent-insensitive and case-insensitive keys.

Python Regular Expressions study guide

5 chapters

1

Write 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.escape for supplied text.
  • search returns the first Match or None; findall collects 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:

  • \d matches a Unicode decimal digit; \D matches a character that is not one.
  • \w matches any character for which str.isalnum() is true, plus _; \W matches its complement.
  • \s matches whitespace, including spaces, tabs, and newlines; \S matches 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 \s use Unicode rules for string patterns.
  • \w includes alphanumeric characters and _, including numeric characters such as "½".
  • Use [0-9] or re.ASCII for ASCII digit rules.
  • The dot excludes newlines unless re.DOTALL is 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; \Z requires the absolute end.
  • re.MULTILINE changes ^ and $, not the string-edge anchors.
  • \b follows 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.
2

Search 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

  • search scans anywhere, match checks the start, and fullmatch checks 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

  • findall returns a list, including an empty list when nothing matches.
  • Capturing-group count determines whether findall returns matches, strings from one group, or tuples.
  • Use (?:...) for structure that should not become an extracted field.
  • finditer keeps 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, and maxsplit to 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.
3

Capture 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.
4

Validate 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 fullmatch when 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.
5

Transform 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.
  • subn returns the new text and the replacement count.
  • split can recognize variable separators; captured separators stay in the list.
  • Pass count, flags, and maxsplit by 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; removeprefix removes 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 len counts 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

5 Walkthroughs

1

Build a pattern you can read

18 steps
Build character rules, repetition, and position tests, then use them together without losing literal text.
  1. 1
    IntroductionDescribe 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.

  2. 2
    ExplanationLet 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())  # fox
    

    In an ordinary literal, "\b" becomes a backspace. Raw syntax passes \b to the engine as a word-boundary test; it does not make regex operators literal.

  3. 3
    TipProtect 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 text expresses the task directly without building a pattern.

  4. 4
    ChallengeFind a supplied version label

    A variable label contains "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.

  5. 5
    ExampleRead two character positions

    Consider [A-Z][0-9] on the text "R58 s9 T4".

    1. [A-Z] requires one uppercase ASCII letter.
    2. [0-9] requires one ASCII digit immediately after it.

    findall returns ['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.

  6. 6
    ExplanationChoose the accepted character set

    \d accepts Unicode decimal digits, \w accepts Unicode alphanumeric characters plus _, and \s accepts whitespace. Capital forms such as \D invert those sets.

    Thus \w+ keeps "café" together and also accepts "½". [a-z]+ stops before "é". Use [0-9] or re.ASCII when a digit field requires ASCII. A dot is wider than a class, but it still excludes newlines unless re.DOTALL is enabled.

  7. 7
    ChallengeRestrict 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]\d would accept it under default Unicode matching. These are character rules; applying them with fullmatch would also require the complete input to be exactly two characters.

  8. 8
    ExplanationCount 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.

  9. 9
    ExampleWatch 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, so findall gives ['<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.

  10. 10
    ExampleGive a digit back to the suffix

    Trace [0-9]+0 against "4800".

    1. The greedy run first consumes all four digits.
    2. The final literal "0" has no text left to use.
    3. 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.

  11. 11
    TipRemove ambiguous ways to divide a run

    Nested repetition such as (a+)+b can 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+b when 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.

  12. 12
    ChallengePredict 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.

  13. 13
    ExplanationDistinguish line endings from string endings

    ^ checks the start, and $ checks the end or the position before a final newline. With re.MULTILINE, they also recognize each line's edges.

    \A and \Z stay tied to absolute string edges. Python 3.14+ also spells the absolute end as \z. On "done\n", done$ can match but done\Z cannot. These tests consume no characters, so the newline never becomes part of the match merely because $ accepts its position.

  14. 14
    ConnectionUse boundaries that follow the word class

    \b tests 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\b finds 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.

  15. 15
    ExampleKeep 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)\Z puts 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.

  16. 16
    ChallengeExplain 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.

  17. 17
    ChallengeBuild 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. fullmatch also rejects an otherwise correct code with extra text or a newline attached.

  18. 18
    RecapRead 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.

2

Choose a result you can use

15 steps
Trace single and repeated matches, then make reused patterns readable with explicit flags.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionMatch the operation to the task
  2. 2
    ExplanationAsk where the pattern must fit
  3. 3
    ExampleUse a match as a slice
  4. 4
    Key InsightEmpty text can be a successful match
  5. 5
    ChallengeReject an embedded number
  6. 6
    ExplanationPredict the list shape before using it
  7. 7
    ExampleRetain the original locations
  8. 8
    TipKeep decimal values in one match
  9. 9
    ChallengeChoose the extraction output
  10. 10
    ExplanationName a pattern you reuse
  11. 11
    ExplanationChoose flags by what changes
  12. 12
    ExampleKeep meaningful spaces in verbose mode
  13. 13
    ChallengeFind why a dot stops early
  14. 14
    ChallengeKeep whole tokens under case changes
  15. 15
    RecapKeep scope and output visible
3

Extract fields from a record

16 steps
Use captures and context tests, then build a parser that reports failed lines and summarizes accepted records.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionGive matched pieces a useful role
  2. 2
    ExampleNumber nested captures from the outside
  3. 3
    ExplanationName the field you want to read
  4. 4
    Key InsightDistinguish a missing field from the last repeat
  5. 5
    ChallengeCapture the whole value under a name
  6. 6
    ExplanationRepeat the text that was found
  7. 7
    ExampleCheck the unit outside the match
  8. 8
    TipHandle a prefix whose width varies
  9. 9
    ChallengeExclude a unit without losing digit prefixes
  10. 10
    ExampleDescribe a complete short log line
  11. 11
    ExampleHandle success and failure in the loop
  12. 12
    TipPreserve the fields a broad trim would change
  13. 13
    ExampleSum values after conversion
  14. 14
    ChallengeKeep damaged lines out of the totals
  15. 15
    ChallengeExtract only equal-code records
  16. 16
    RecapCarry fields safely into code
4

Build a validator from a written rule

13 steps
Combine complete-string format checks with preprocessing, semantic checks, and useful limits.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionDecide what acceptance means
  2. 2
    ExampleAllocate the total character count
  3. 3
    ExplanationApply the format to every character
  4. 4
    ConnectionNormalize only accepted differences
  5. 5
    ChallengeTest both length boundaries
  6. 6
    ExampleCheck whether a date exists
  7. 7
    ExampleKeep spelling and range as separate checks
  8. 8
    TipBound the input and the matching work
  9. 9
    ConnectionSeparate a usable shape from real-world verification
  10. 10
    ChallengeRepair a range check with leading zeros
  11. 11
    ChallengeValidate an agreed code policy
  12. 12
    Key InsightTest failure paths as well as accepted values
  13. 13
    RecapLet each check answer its own question
5

Transform text without losing its meaning

17 steps
Use substitutions, deliberate cleaning steps, and Unicode keys while preserving the values you need.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionChoose the form you want to keep
  2. 2
    ExampleReorder captured fields
  3. 3
    ExplanationCompute from each match
  4. 4
    ExampleDecide whether separators belong in the result
  5. 5
    ChallengeLimit a computed replacement
  6. 6
    TipRemove a prefix instead of a character set
  7. 7
    ExampleTranslate selected punctuation
  8. 8
    ConnectionPreserve values before broad cleanup
  9. 9
    ChallengeKeep a decimal measurement intact
  10. 10
    ExplanationInspect stored characters before matching
  11. 11
    ExplanationChoose among the four normal forms
  12. 12
    ExampleBuild a key for caseless comparison
  13. 13
    ExampleRemove decomposed accents for a loose key
  14. 14
    ChallengeExplain unequal visible spellings
  15. 15
    TipCorrect decoding before normalization
  16. 16
    ChallengePut a cleaning pipeline in order
  17. 17
    RecapSeparate display values from comparison keys

Python Regular Expressions practice questions

50 Practice Questions in 5 sets

Set 1: Read patterns and predict results10 Practice Questions

Question 1 of 10

What does re.findall(r"\b([A-Za-z]+)\s+\1\b", "go go gone go") return?
  1. ['go']
  2. ['go go']
  3. ['go', 'gone']
  4. ['go', 'go']
Show answerHide answer
Answer: A
The pattern finds one doubled word, "go go", because the backreference requires the first captured text again. Since the pattern has one capture, findall returns only "go". The final two words do not repeat, and a second match cannot overlap the first one.

Question 2 of 10

What does re.findall(r"(\w+):([0-9]+)", "oak:6 pine:14") return?
  1. ['oak:6', 'pine:14']
  2. ['6', '14']
  3. [('oak', '6'), ('pine', '14')]
  4. [('oak', 6), ('pine', 14)]
Show answerHide answer
Answer: C
Two capturing groups make each result a tuple containing the captured name and numeric text. The colon belongs to the full match but neither group. Digits remain strings; findall does not infer integer types or convert the extracted values automatically.

Question 3 of 10

For m = re.fullmatch(r"(\d)+", "846"), what is m.group(1)?
  1. '846'
  2. '6'
  3. '8'
  4. ('8', '4', '6')
Show answerHide answer
Answer: B
The group participates three times and retains the text of its last repetition, "6". The whole match is "846", but that is group 0. To save the whole digit run in group 1, put the quantifier inside its parentheses: (\d+).

Question 4 of 10

What does re.findall(r"[0-9]{2,3}", "4 83 61728") return?
  1. ['83', '617', '28']
  2. ['83', '617']
  3. ['83', '61728']
  4. ['83', '61', '72']
Show answerHide answer
Answer: A
The one-digit piece cannot match, "83" supplies two digits, and greedy repetition first takes "617" from the longer run. The search then resumes and finds "28". The upper bound limits each match; it does not reject a longer digit run as a whole.

Question 5 of 10

What does re.match(r"[0-9]+", "code 58") return?
  1. A Match containing '58'
  2. A Match containing ''
  3. None
  4. An empty list []
Show answerHide answer
Answer: C
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

A search must find the exact text "v2.8+" inside a message. What expression safely turns this supplied text into a literal regex pattern?
  1. r"v2.8+"
  2. re.escape("v2.8+")
  3. "v2.8+".strip()
  4. re.compile("v2.8+")
Show answerHide answer
Answer: B
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

What does re.findall(r"[A-Z][0-9]", "D43 e8 F2") return?
  1. ['D43', 'F2']
  2. ['D4', 'e8', 'F2']
  3. ['F2']
  4. ['D4', 'F2']
Show answerHide answer
Answer: D
Each class matches one character, so the pattern takes only "D4" from "D43" and also finds "F2". Lowercase "e" fails [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

A code must contain one uppercase ASCII letter followed by exactly three ASCII digits, with nothing else. What call enforces this rule on s?
  1. re.search(r"[A-Z][0-9]{3}", s)
  2. re.match(r"[A-Z][0-9]{3}", s)
  3. re.fullmatch(r"[A-Z][0-9]{2,3}", s)
  4. re.fullmatch(r"[A-Z][0-9]{3}", s)
Show answerHide answer
Answer: D
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

What does re.split(r"[;|]\s*", "lime; pear|plum") return?
  1. ['lime', ' pear', 'plum']
  2. ['lime', ';', 'pear', '|', 'plum']
  3. ['lime; pear', 'plum']
  4. ['lime', 'pear', 'plum']
Show answerHide answer
Answer: D
Inside the class, both the semicolon and vertical bar are literal separators. The following \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

A cleanup step runs re.sub(r"[^\w\s]", "", "load=6.25 kg"), then extracts all [0-9]+ runs and sums their integer values. What total results?
  1. 31
  2. 625
  3. 6.25
  4. 6
Show answerHide answer
Answer: B
Cleanup deletes the equals sign and decimal point, producing "load625 kg". The numeric extraction therefore sees one run, "625", and its integer sum is 625. Adding 6 and 25 would describe extraction before cleanup; the operation order changes the data.
Set 2: Choose functions and validate formats10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

What normalization form composes canonical equivalents while preserving the distinction between "x²" and "x2"?
  1. NFC
  2. NFKC
  3. NFD
  4. NFKD
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

What text does re.search(r"May|Mayday", "Mayday call").group() return?
  1. 'Mayday'
  2. 'Mayday call'
  3. 'May'
  4. 'day'
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A field must contain exactly two ASCII digits. What test rejects both Arabic-Indic digits and an extra trailing character?
  1. re.fullmatch(r"[0-9]{2}", s)
  2. re.fullmatch(r"\d{2}", s)
  3. re.search(r"[0-9]{2}", s)
  4. re.match(r"[0-9]{2}", s)
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

What flag allows the dot in r"BEGIN.*END" to match across newline characters?
  1. re.MULTILINE
  2. re.VERBOSE
  3. re.ASCII
  4. re.DOTALL
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

Given m = re.search(r"[0-9]+", "bay 742 east"), what are m.span() and the length of m.group()?
  1. (4, 6) and 3
  2. (4, 7) and 3
  3. (4, 7) and 4
  4. (5, 8) and 3
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A parser uses 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?
  1. P.fullmatch(line).groupdict()
  2. P.fullmatch(line.rstrip("\n")).groupdict()
  3. P.fullmatch(line.strip()).groups()
  4. P.findall(line.rstrip("\n"))
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

For m = re.fullmatch(r"(?P<whole>[0-9]+)(?:\.(?P<part>[0-9]+))?", "93"), what is m.groupdict()?
  1. {'whole': '93', 'part': None}
  2. {'whole': '93', 'part': ''}
  3. {'whole': 93, 'part': 0}
  4. {'whole': '93'}
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A field passes 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?
  1. Apply the same shape pattern with re.ASCII.
  2. Require exactly 10 code points with len(s).
  3. Replace the hyphens and convert the digits to int.
  4. Call date.fromisoformat(s) and handle ValueError.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

An identifier must be 4–9 characters, start with a lowercase ASCII letter, and then contain lowercase ASCII letters or digits. It must reject a final newline. What check implements all of this?
  1. re.fullmatch(r"[a-z][a-z0-9]{4,9}", s)
  2. re.search(r"^[a-z][a-z0-9]{3,8}$", s)
  3. re.fullmatch(r"[a-z][a-z0-9]{3,8}", s)
  4. re.fullmatch(r"[a-z0-9]{4,9}", s)
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

For 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?
  1. '90 120'; \10 refers to group 10.
  2. '90 12'; \10 inserts a newline.
  3. '90 12'; \10 refers to group 10.
  4. '90 120'; \10 means group 1 plus zero.
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?
  1. re.search(needle, message) is not None
  2. message.startswith(needle)
  3. re.fullmatch(re.escape(needle), message) is not None
  4. needle in message
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A Python 3.11+ validator freezes on long runs of "m" with no final "n" because it uses (m+)+n. What rewrite preserves its accepted complete strings and removes the ambiguous nested repetition?
  1. (?>(m+)+n)
  2. (m+?)+n
  3. m+n
  4. (m*)+n
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

What does re.findall(r"^id=[0-9]+$", "id=31\nxid=44\nid=57\n", flags=re.MULTILINE) return?
  1. ['id=31', 'id=57']
  2. ['id=31']
  3. ['id=31', 'id=44', 'id=57']
  4. ['id=31\n', 'id=57\n']
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

You need every numeric match and its original span in a long message. What loop keeps that information available one match at a time?
  1. for m in re.findall(r"[0-9]+", text):
  2. for m in re.finditer(r"[0-9]+", text):
  3. for m in re.findall(r"([0-9]+)", text):
  4. for m in re.split(r"[0-9]+", text):
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A compiled pattern uses 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()?
  1. r"A[ ]B\#C"
  2. r"A B#C"
  3. r"A\sB\#C"
  4. r"A[ ]B#C"
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

What does re.findall(r"\b[0-9]+\b(?! kg)", "16 kg; 24 km; 8 kg") return, and why is the boundary after the digits needed?
  1. ['1', '24']; it prevents a shorter digit prefix from passing.
  2. ['24']; it makes the unit part of the returned text.
  3. ['16', '24', '8']; it makes the lookahead optional.
  4. ['24']; it prevents a shorter digit prefix from passing.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A whole-line parser accepts records "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?
  1. {'INFO': 2, 'ERROR': 1} and 1 rejected.
  2. {'INFO': 11, 'ERROR': 12} and 0 rejected.
  3. {'INFO': 11, 'ERROR': 12} and 1 rejected.
  4. {'INFO': '74', 'ERROR': '12'} and 1 rejected.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A field is a decimal integer from 0 through 180, with no leading zeros except "0" itself. After an appropriate input-length limit, what check preserves both the spelling and range rules?
  1. re.fullmatch(r"[0-9]{1,3}", s) is not None and int(s) <= 180
  2. re.fullmatch(r"0|[1-9][0-9]{0,2}", s) is not None and int(s) <= 180
  3. re.fullmatch(r"0|[1-9][0-9]{0,2}", s) is not None
  4. re.fullmatch(r"[0-9]{1,3}", s) is not None and int(s) < 180
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A string may begin with exactly one literal prefix "tag:". What method removes that prefix once while preserving any following "t", "a", "g", or ":" characters?
  1. s.strip("tag:")
  2. s.removeprefix("tag:")
  3. s.lstrip("tag:")
  4. s.replace("tag:", "")
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

For s = "jalapen\u0303o", what happens when re.findall(r"\w+", s) runs before and after NFC normalization?
  1. Before: ['jalapeño']; after: ['jalapeño'].
  2. Before: ['jalapen', 'o']; after: ['jalapeno'].
  3. Before: ['jalapen', 'o']; after: ['jalapeño'].
  4. Before: ['jalapeño']; after: ['jalapen', 'o'].
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

What raw regex pattern matches the literal text "[ok]"?
  1. r"\[ok\]"
  2. r"[ok]"
  3. r"(ok)"
  4. r"[ok]+"
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

What does re.findall(r"\w+", "½ café _x") return with default string-pattern flags?
  1. ['café', '_x']
  2. ['caf', 'x']
  3. ['½', 'café', '_x']
  4. ['½', 'caf', 'x']
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A filter uses 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?
  1. It is rejected; use re.fullmatch(r"[0-9]+", s).
  2. It is accepted; use re.match(r"[0-9]+", s).
  3. It is accepted; use re.fullmatch(r"[0-9]*", s).
  4. It is accepted; use re.fullmatch(r"[0-9]+", s).
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A report must return whole tokens "warns" and "errors" from "warns/errors". Why does re.findall(r"(warn|error)s", text) lose the final "s", and what preserves complete tokens?
  1. One capture selects its own text; use r"(warn|error)(s)".
  2. One capture selects its own text; use r"(?:warn|error)s".
  3. The alternatives are lazy; use r"(warn|error)s+".
  4. The slash ends the capture; use r"(warns)|(errors)".
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

For m = re.fullmatch(r"((?P<left>[0-9]+)):(?P<right>[0-9]+)", "27:81"), what do m.group(2) and m.group("right") contain?
  1. '81' and '81'
  2. '27' and '81'
  3. '27:81' and '81'
  4. '27' and 81
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A Python pattern (?<=ID=|KEY=)[0-9]+ fails to compile. What rewrite extracts the numeric values after either prefix from prose while avoiding the width error?
  1. re.findall(r"(?<=ID=|KEY=)([0-9]+)", text)
  2. re.findall(r"(?:ID=|KEY=)[0-9]+", text)
  3. re.findall(r"(?<=ID=)(?:KEY=)?[0-9]+", text)
  4. re.findall(r"(?:ID=|KEY=)([0-9]+)", text)
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A code validator applies .strip().upper() before checking r"[A-Z]{2}[0-9]{3}" with fullmatch. How does it handle " zx408\n"?
  1. It rejects the original leading space.
  2. It rejects the original final newline.
  3. It accepts the normalized value 'ZX408'.
  4. It accepts and stores ' zx408\n' as the normalized value.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A service accepts an optional plus sign only at the start, followed by 3–8 ASCII digits whose first digit is nonzero. After removing accepted spaces and hyphens, what whole-input check on cleaned enforces this policy?
  1. re.fullmatch(r"\+?[1-9][0-9]{2,7}", cleaned)
  2. re.fullmatch(r"\+?[0-9]{3,8}", cleaned)
  3. re.search(r"\+?[1-9][0-9]{2,7}", cleaned)
  4. re.fullmatch(r"\+?[1-9][0-9]{3,8}", cleaned)
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

What does re.subn(r"([0-9]+)g\b", lambda m: str(int(m[1]) + 5) + "g", "8g 23g 4kg", count=1) return?
  1. ('13g 23g 4kg', 1)
  2. ('13g 28g 4kg', 2)
  3. ('13g 23g 9kg', 2)
  4. ('85g 23g 4kg', 1)
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A search key must equate "FI" with "fi" and "Straße" with "STRASSE", while the original spelling stays available for display. What key expression handles both comparisons?
  1. unicodedata.normalize("NFC", s).lower()
  2. unicodedata.normalize("NFD", s).casefold()
  3. unicodedata.normalize("NFKC", s).lower()
  4. unicodedata.normalize("NFKC", s).casefold()
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

A pattern must accept "log" followed by one or more ASCII digits. What pattern expresses that repetition?
  1. r"log[0-9]*"
  2. r"log[0-9]+"
  3. r"log[0-9]?"
  4. r"(?:log[0-9])+"
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?
  1. re.fullmatch(r"open|closed", s)
  2. re.search(r"^(?:open|closed)$", s)
  3. re.match(r"(?:open|closed)", s)
  4. re.search(r"\b(?:open|closed)\b", s)
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

What complete text is matched by re.fullmatch(r"[0-9]+?0", "5600"), and what changes if the pattern becomes [0-9]++0 in Python 3.11+?
  1. Lazy: '560'; possessive: no match.
  2. Lazy: '5600'; possessive: '5600'.
  3. Lazy: no match; possessive: '5600'.
  4. Lazy: '5600'; possessive: no match.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

What does re.sub(r"x", "-", "XxxX", flags=re.IGNORECASE, count=2) return?
  1. 'X--X'
  2. '----'
  3. '--xX'
  4. '-xxX'
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A script extracts quantities from "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?
  1. Use r"[0-9]+(?:\.[0-9]+)?" and convert each result to float.
  2. Use r"([0-9]+)(\.[0-9]+)?" and convert each result to float.
  3. Use r"[0-9]+" and convert each result to float.
  4. Keep the pattern and ignore every empty result before conversion.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A parser counts only records matching 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?
  1. 1 accepted and 3 rejected.
  2. 4 accepted and 0 rejected.
  3. 3 accepted and 1 rejected.
  4. 2 accepted and 2 rejected.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

What does re.findall(r"(?<=@)[A-Za-z]+", "@north and @south") return?
  1. ['@north', '@south']
  2. ['@', '@']
  3. ['north and', 'south']
  4. ['north', 'south']
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A validator for an ASCII integer from 1 through 75 uses 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?
  1. re.search(r"[1-9][0-9]?", s) is not None and int(s) <= 75
  2. re.fullmatch(r"[1-9][0-9]?", s) is not None and int(s) <= 75
  3. re.fullmatch(r"[0-9]{1,2}", s) is not None and int(s) <= 75
  4. re.fullmatch(r"[1-9][0-9]?", s) is not None and int(s) < 75
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A comparison pipeline deletes every character outside \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?
  1. NFC always removes accents; replace NFC with NFKC afterward.
  2. Whitespace joins accents to letters; collapse it after NFC.
  3. Combining accents are deleted first; apply NFC before that deletion.
  4. The word class rejects accented letters; add re.IGNORECASE.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A key function applies NFD, removes characters with nonzero 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?
  1. 'aland' and 'koge'; every accented-looking letter decomposes.
  2. 'aland' and 'køge'; "Å" decomposes, while "ø" does not.
  3. 'åland' and 'køge'; NFD only changes letter case.
  4. 'aland' and 'kge'; the word class removes the slashed letter.
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

77 Key Terms, each with its definition

A

Aggregation
Aggregation combines values from multiple records into a summary such as a count, total, or frequency distribution.
Aggregation with Counter reports how many accepted log records have each severity level.
Allowlist
An allowlist describes the characters or structures accepted by a rule, making the permitted input explicit.
An allowlist of ASCII letters and digits excludes unseen punctuation without naming each forbidden mark.
Alternation
Alternation offers pattern branches separated by |, trying them in order until one permits the whole pattern to match.
Alternation in June|Jun can return "June" before the shorter branch is attempted.
Anchor
An anchor is a zero-width pattern test for a position such as the start or end of a string or, with a flag, a line.
The anchor \Z rejects a match that ends before a newline still present in the input.
ASCII
ASCII is a character standard containing 128 characters, including unaccented Latin letters, digits, and common controls.
Using the ASCII range [0-9] keeps a code's digits restricted to the characters "0" through "9".
Atomic group
An atomic group discards its internal backtracking positions after it succeeds, preventing later failure from reopening those choices.
An atomic group around the inner run in (?>a+)+b removes the ambiguous divisions of that run.

B

Backreference
A backreference requires the actual text captured by an earlier group to match again under the active matching rules.
A backreference distinguishes equal digits such as "88" from different digits such as "89".
Backtracking
Backtracking is the engine's process of revisiting earlier matching choices when a later part of the pattern fails.
Backtracking lets the digit run in [0-9]+0 return a final zero to the literal suffix.
Blocklist
A blocklist names forbidden characters or structures, requiring the rule to anticipate each form it intends to reject.
A blocklist that mentions ordinary spaces can miss a non-breaking space in supplied text.
Boundary case
A boundary case is an input at or near a rule's limit that helps expose mistakes in counts, ranges, or edge handling.
A boundary case one character longer than the maximum can reveal a misplaced quantifier count.

C

Canonical equivalence
Canonical equivalence relates Unicode sequences representing the same abstract characters through canonical composition or decomposition.
Canonical equivalence connects precomposed "é" with "e" followed by a combining acute accent.
Capturing group
A capturing group is a parenthesized pattern part that remembers its matched text and receives a numeric group position.
A capturing group around the complete digit run in ([0-9]+) saves all digits together.
Case folding
Case folding maps Unicode case variants to text suitable for caseless comparison and can make changes beyond lowercasing.
Case folding maps "Straße" and "STRASSE" to the same key while display text stays separate.
Catastrophic backtracking
Catastrophic backtracking is explosive growth in matching work when a pattern explores many equivalent divisions of text.
A missing final "b" can trigger catastrophic backtracking in (a+)+b on a long run of "a".
Character class
A character class is a set written in square brackets that accepts exactly one character from the specified set.
The character class [A-F] accepts the initial "B" in "B29" without consuming its digits.
Code point
A code point is a numeric position in Unicode's character space, written in a form such as U+00E9 for precomposed "é".
A Python string's length counts each code point even when several combine into one visible character.
Combining mark
A combining mark is a Unicode character that combines with another character, such as the separate acute accent following "e".
A combining mark can fall outside a \w+ match before NFC composes the accented letter.
Compatibility mapping
A compatibility mapping replaces a Unicode character with a related form while potentially removing a meaningful distinction.
A compatibility mapping makes a superscript digit ordinary, which may be unsuitable for display text.
Compiled pattern
A compiled pattern is a reusable Pattern object made with re.compile, carrying its pattern and matching flags together.
Give a compiled pattern the name TIME when several parts of a program share that format rule.

E

Escaping
Escaping protects a special character so it is interpreted literally in the syntax where it will be used.
Escaping supplied search text with re.escape prevents its period from acting as a wildcard.

F

findall
The findall function collects non-overlapping matches in a list whose item shape depends on the pattern's capturing groups.
With two captures, findall gives tuples so a name and its numeric text stay paired.
finditer
The finditer function returns an iterator yielding a Match object for each non-overlapping match in input order.
Use finditer to highlight numeric matches while keeping each result's original span.
Fixed-width pattern
A fixed-width pattern matches a known number of characters whenever it succeeds, as required inside Python lookbehind.
The fixed-width pattern a|b works in lookbehind because both branches take one character.
Flag
A flag is an option that changes a specific aspect of matching, such as case sensitivity, anchor positions, or dot behavior.
The flag re.DOTALL lets a dot consume a line break between two required markers.
Format
A format is the required written structure of a value, including permitted characters, field lengths, and separators.
The format YYYY-MM-DD fixes a date's field widths without establishing that the day exists.
Full match
A full match is a successful pattern fit that covers the entire string, leaving no unmatched prefix or suffix.
A full match of [0-9]+ fails on "73 items" because the words remain outside the digit run.

G

Greedy quantifier
A greedy quantifier first takes as much matching text as possible, then can give some back so the rest of the pattern succeeds.
The greedy quantifier in <.+> can span several angle-bracketed pieces in one match.
Group 0
Group 0 is the complete text matched by a pattern, including parts outside its individual numbered or named captures.
Group 0 keeps the separators in a date match even when separate captures select just the fields.
groupdict
The groupdict method returns a dictionary linking every named capture to its captured string or its absent-value fallback.
Use groupdict to turn a matched log line into fields before converting its numeric count.

I

Input-length limit
An input-length limit is a bound checked before processing so an oversized value does not reach an expensive matching operation.
An input-length limit rejects an enormous form value before the validator evaluates its regex.

L

Lazy quantifier
A lazy quantifier first tries as little text as possible and expands when later parts need more for an overall match.
The lazy quantifier in <.+?> stops at an earlier closing delimiter when that allows success.
Line-oriented parsing
Line-oriented parsing processes each text line as an individual record with its own matching and failure-handling step.
Line-oriented parsing lets a log reader report the line number of a damaged entry.
Literal character
A literal character in a pattern stands for itself instead of acting as an instruction to the regex engine.
The letter "t" is a literal character in cat, while the dot in c.t is a wildcard.
Lookahead
A lookahead checks following text at the current position without consuming it, either requiring it or forbidding it.
A lookahead for " kg" extracts the number while leaving the space and unit outside the match.
Lookbehind
A lookbehind checks text immediately before the current position without consuming it and must have fixed width in Python.
A lookbehind for "#" lets a tag pattern return only the letters after the hash sign.

M

Match object
A Match object represents a successful pattern fit and provides the matched text, captured groups, and index positions.
Check for a Match object before calling .group() because a failed search returns None.
Match span
A match span is a pair of indices marking the first matched position and the exclusive position just after the match.
The match span (3, 6) lets text[3:6] recover exactly the same three matched characters.
Metacharacter
A metacharacter is a pattern character with a special role, such as grouping, repetition, or matching a position.
Escape the metacharacter "+" when a product label must contain that exact punctuation mark.

N

Named group
A named group is a capture declared with (?P<name>...) that supports meaningful field access as well as numeric access.
A named group called "source" lets a log parser read m["source"] without counting parentheses.
Negated class
A negated class accepts a character outside its listed set and is marked by a caret immediately after the opening square bracket.
The negated class [^,] can consume a newline because it excludes commas only.
NFC
NFC is the Unicode normal form that applies canonical decomposition and then composes sequences where a canonical composition exists.
NFC makes two canonically equivalent spellings of "café" equal without removing their accent.
NFD
NFD is the Unicode normal form that decomposes canonical equivalents into component sequences without compatibility mappings.
NFD separates the acute accent in "é" so an accent-key function can inspect the mark.
NFKC
NFKC is the Unicode normal form that applies compatibility mappings and then composes the resulting canonical sequences.
NFKC turns fullwidth digits into ordinary digits but can also change "x²" into "x2".
NFKD
NFKD is the Unicode normal form that applies compatibility mappings and leaves the result canonically decomposed.
NFKD separates accents while also expanding a compatibility ligature such as "fi" into "fi".
Non-capturing group
A non-capturing group organizes pattern structure with (?:...) without saving a field or receiving a capture number.
A non-capturing group keeps plural tokens whole in findall(r"(?:cat|dog)s", text).
Non-overlapping matches
Non-overlapping matches are results that do not reuse characters from an earlier match, scanning onward from each match's end.
Non-overlapping matches for "ana" in "banana" include only the first possible occurrence.
Normalization
Normalization converts Unicode text to a specified standard form so equivalent sequences share a consistent representation.
Normalization to NFC before matching keeps a decomposed accent attached to the extracted word.
Numeric conversion
Numeric conversion turns extracted numeric text into a number so code can calculate with its value instead of treating it as a string.
Numeric conversion with float lets the extracted text "9.4" contribute to a measurement total.

O

Optional capture
An optional capture is a group that may not participate in a successful match and then has value None in the Match object.
An optional capture for a decimal fraction is absent when the input is the whole number "64".

P

PatternError
PatternError is the Python 3.13+ exception for invalid regex syntax; the compatible earlier name is re.error.
A PatternError points to an unpaired opening parenthesis when the pattern omits its closing partner.
Possessive quantifier
A possessive quantifier takes matching text without giving it back during later matching attempts, in Python 3.11 and later.
A possessive quantifier in a++a consumes the whole "a" run and leaves nothing for its suffix.
Precedence
Precedence is the ordering that determines how pattern operators combine when grouping does not state the structure explicitly.
Alternation's low precedence makes ^up|down$ apply a different anchor to each branch.
Prefix match
A prefix match is a successful pattern fit that begins at the start of the string without necessarily covering its end.
A prefix match for [0-9]+ can accept "73" at the beginning of "73 items".
Preprocessing
Preprocessing applies agreed transformations to input before later checks or extraction, such as trimming accepted edge spaces.
Preprocessing a case-insensitive code with .strip().upper() can make accepted variants consistent.

Q

Quantifier
A quantifier sets how many times the preceding pattern item may repeat, using a symbol or a count in braces.
The quantifier {2,5} repeats the digit class in [0-9]{2,5} two through five times.

R

Range
A range in a character class includes characters between two endpoints in code-point order, written with a hyphen.
The range [0-9] accepts ASCII digits, so a fullwidth digit does not satisfy that class.
Raw string
A raw string is a Python literal whose backslashes reach the resulting string unchanged for later interpretation.
A raw string such as r"\bfox\b" passes the boundary escapes to the regex engine.
Record
A record is a structured collection of related fields extracted from one input item, often represented by a dictionary.
A log record can hold a date, level, source, and message under names used by later code.
ReDoS
ReDoS is denial of service caused by a regex taking excessive time on input that triggers expensive matching behavior.
Ambiguous nested repetition can create ReDoS risk when a server accepts long untrusted strings.
Regex splitting
Regex splitting divides a string at separators described by a pattern, optionally retaining separators placed in capturing groups.
Regex splitting handles both commas and semicolons in a short list with variable separators.
Regular expression
A regular expression is a pattern describing text that can vary, using rules for its characters, repeated pieces, and positions.
The regular expression [0-9]+ finds a digit run even when its length changes between messages.
Rejected line
A rejected line is an input record that fails the parser's required shape and is counted or retained for inspection.
A rejected line remains outside level totals while its number helps locate the input problem.
Replacement function
A replacement function receives a Match object and returns the text that should replace that particular match.
A replacement function converts a captured count to an integer before computing its new value.
Replacement template
A replacement template is a string interpreted by sub that can insert captured text through references such as \g<name>.
A replacement template reorders captured day, month, and year fields into a different date spelling.

S

Scoped flag
A scoped flag changes matching behavior inside one pattern group without applying the change to the rest of the pattern.
The scoped flag in (?i:p)ython allows an uppercase first letter but preserves the suffix's case.
Semantic validation
Semantic validation checks a value's meaning, such as a real calendar date or an allowed numeric range, after its spelling fits.
Semantic validation rejects "2027-02-30" even though it has the required date shape.
Shorthand class
A shorthand class is an escape such as \d, \w, or \s that names a commonly used character set in a pattern.
The shorthand class \s can match a non-breaking space as well as an ordinary space.
subn
The subn function performs regex substitution and returns a tuple containing the new text and the number of replacements made.
The count from subn shows how many whitespace runs were replaced in a cleaning pass.
Substitution
Substitution replaces matched regions with new text and returns a new string while leaving the original value unchanged.
Substitution can wrap every extracted number in parentheses without changing the surrounding words.

T

Text cleaning
Text cleaning transforms inconsistent strings into an agreed form while preserving the information required for their intended use.
Text cleaning can standardize curly quotes before storing a readable display value.
Translation table
A translation table maps individual characters to replacements or deletion and is applied to a string by str.translate.
A translation table can replace both curly double quotes with one straight-quote character.

V

Validation
Validation checks whether an input meets specified requirements before the program accepts or processes it for a purpose.
Validation with fullmatch rejects a correct-looking code embedded in extra unwanted text.
Verbose mode
Verbose mode lets a regex include layout whitespace and comments while requiring meaningful spaces to be written explicitly.
In verbose mode, [ ] keeps a required space that ordinary layout whitespace would lose.

W

Whitespace collapse
Whitespace collapse changes each whitespace run to a simpler separator, often one space, and may also trim string edges.
Whitespace collapse can remove record boundaries when a newline is treated like an ordinary space.
Word boundary
A word boundary is a position where a word character meets a non-word character or the edge of the string.
A word boundary follows "fox" in "fox's" because the apostrophe is not a word character.
Word character
A word character in a default Python string pattern is a Unicode alphanumeric character or an underscore.
A word character can be "é", "½", or "_", so \w is broader than an ASCII letter range.

Z

Zero-width assertion
A zero-width assertion tests a position or nearby context while consuming no characters from the matched input.
A zero-width assertion can check a unit before the next pattern part consumes that same text.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started