Skip to main content
6 day streak
Skip to lesson
CareerPetalPython field guide
Loading progress...
Course contents
PYTHON FIELD GUIDE

Course contents 72 topics / 15 parts

Full course overviewOriginal coding practice / separate server checks

Essentials first, then internals and engineering trade-offs.

LESSON 21 / FILES AND STANDARD LIBRARY

Regular expressions and structured matching

Use bounded patterns for text structure, not as a universal parser.

IntermediateTutorial 14 min core+12 min deep divePython 3.11+ / 2026-10-27
Saved work unavailable

Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.

Before you start

Learners who can read small Python functions and want to apply the listed foundations.

Explore the connected curriculum and preparation map

Lesson content version 2026-10-27. Suggested core budget: 14 minutes; optional deep dive: 12 more minutes. These are reading/practice estimates, not a timed test.

Suggested preparation and repair routes

If an example or checkpoint feels unclear, revisit the relevant foundation and return. These links do not lock the lesson or claim you passed a prerequisite.

Actual runtime and local-lab boundaries

Browser Python 3.13: fresh isolated worker, 4-second execution, 16 KiB output, 256 MiB Python heap; no outbound network, host processes, interactive input or package installation.

Supported snippets run in the browser; temporary files and SQLite data disappear after each run. Models are labelled conceptual, not traces of your edited source. Full operating-system/framework/cloud labs need separate approval.

Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.

YOU WILL BE ABLE TO
  • Explain choose a pattern or a simpler tool
  • Apply use raw strings and groups
  • Reason about security and semantics
01

Choose a pattern or a simpler tool

A regular expression describes a small shape of text. Choose the matching operation as well as the pattern: finding a piece and validating a whole value are different tasks.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

A short event tag has repeated structure that a pattern can express clearly. Start with strings, method calls and None. If the task is just checking a literal prefix, startswith is simpler and easier to review than a regex.

Words you will see

Pattern
A description of text that may match.
Match object
The successful result, with positions and captured text.
fullmatch
A match operation that must consume the entire input value.

Choose what success means

The fixture contains extra text on both sides of api-042. search moves along until it finds lowercase letters, a hyphen and three ASCII digits. group() returns only that matched slice. The existence of this slice does not validate the enclosing string.

fullmatch cannot skip the x- prefix or -y suffix, so it returns None. Testing is None makes failure explicit before using group. A raw string, marked with r before the quote, reduces Python backslash processing; it does not turn off regex operators.

Choose a smaller tool when possible

startswith answers a fixed-prefix question without interpreting pattern syntax. split is useful for separating known delimiters. A JSON or CSV parser understands its own format; a homemade regex is not a replacement for a nested-format parser.

This example processes only short literal strings. An empty value has no match for this pattern. In a real boundary, cap the input before matching and state whether spaces and non-ASCII letters are permitted. A successful shape check is not permission to access a service.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. text = 'x-api-042-y'

    Keep the prefix and suffix so the two operations have different answers.

  2. found = re.search(pattern, text)

    Find api-042 inside the fixture.

  3. print(found.group())

    Print the successful slice, not the original text.

  4. print(re.fullmatch(pattern, text) is None)

    Print True because the whole input cannot fit.

Use startswith, split or a real format parser when they express the task. Regex is useful for constrained extraction or validation of a small text shape. search finds a match anywhere; fullmatch requires the entire string to match.

Conceptual validation boundary, not a live matcher trace

Conceptual reasoning steps for the original example, not a live trace of your edited Python.

  1. BoundReject an input longer than the accepted identifier size.
  2. Match allfullmatch requires both ends of this value to fit.
  3. ExtractRead fields only from a successful match object.
Predict before you run

Which operation rejects the surrounding x- and -y?

Find a piece or validate a valuePYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Remove the surrounding text.

Try: Set text = 'api-042'.

The fullmatch-is-None result becomes False; both match operations now succeed.

Try a literal-prefix alternative.

Try: Change the final startswith argument to 'worker-'.

The final result becomes False without using any regex.

Before you move on

Would search and fullmatch agree on the fresh value 'job-007!'?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

No. search can find job-007, while fullmatch rejects the trailing exclamation mark. Neither operation removes it from the original string.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
02

Use raw strings and groups

A capture group gives a name to part of a successful match. Validation decides whether the value fits; extraction then reads its meaningful parts.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

After checking a small record, you usually need its fields rather than a yes/no answer. Named groups connect the code to field meaning and avoid brittle numeric group positions. Know basic if statements and integer conversion first.

Words you will see

Named group
A captured subpattern accessed by a descriptive name.
Quantifier
An operator such as {1,8} that limits how often a piece repeats.
Compilation
Preparing a reusable pattern object with matching methods.

Separate the shape from the meaning

The kind group accepts one to eight lowercase ASCII letters. The colon is literal. The count group requires one or two ASCII digits. fullmatch checks the entire job:04 value and returns a match whose groups contain job and 04.

int converts 04 to integer 4, so leading-zero formatting is lost deliberately. Keep group text instead if a code's exact spelling matters. A digit shape alone does not establish a sensible quantity range; add a numeric check if, for example, zero is forbidden.

Handle absence before extraction

job: has no count digits and returns None. The if guard makes the group calls safe. Increasing a quantifier changes the accepted language, not just output formatting. [0-9] is deliberately narrower than \d, which can accept other Unicode decimal digits.

Compiling is useful when the same pattern is reused or named for clarity. It does not prove matching will be cheap for arbitrary patterns. For a delimiter-only task, partition plus explicit field checks may be easier than group syntax. All fixtures here are bounded editor strings.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. match = pattern.fullmatch('job:04')

    Validate two bounded fields separated by one colon.

  2. if match is not None:

    Enter only on successful validation.

  3. print(int(match.group('count')))

    Convert the captured 04 string into integer 4.

  4. print(pattern.fullmatch('job:') is None)

    Show that an absent number is not an empty valid field.

A raw string reduces Python string escaping, but regex escaping still applies. Named groups make extraction readable. Test empty input, extra prefixes/suffixes and unexpected Unicode characters; a digit class may include more than ASCII digits.

Predict before you run

Why is the second output 4, not 04?

Extract a checked fieldPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Keep formatting.

Try: Print match.group('count') without int.

The second line becomes 04.

Cross the digit-width boundary.

Try: Change the first value to 'job:123'.

No group lines run, because three digits exceed {1,2}; the final result still prints True.

Before you move on

For 'box:00', what does count contain, and does the regex forbid zero?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

The group contains the string '00', which converts to 0. This pattern permits zero; a positive-count rule needs another explicit check.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
03

Validate an event identifier

A whole identifier can be checked and split into named fields in one match. Keep the original text when leading zeros carry meaning.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Event identifiers often need both a validation decision and two display fields. The original demonstration connects the two operations. It uses fixed small fixtures; a caller accepting arbitrary input must add its own length cap before this pattern.

Words you will see

ASCII range
An explicit range such as 0 through 9, not all Unicode digits.
Field width
The permitted number of characters in one field.
Literal separator
A character, here a hyphen, required between fields.

Read the original identifier from left to right

The service group consumes one or more lowercase letters. A literal hyphen ends that field. The number group consumes exactly three ASCII digits. For api-042, service is api and number is 042. print joins them with a space but does not change either group.

prefix-api-042 has two hyphens. The service group cannot consume a hyphen, and the number must follow the first separator immediately, so fullmatch fails. A search would find a valid-looking suffix and therefore answer a different question.

Keep the demonstration's boundary honest

The + permits arbitrarily long service names in principle. This literal demonstration is bounded by its fixture, not by a general regex execution deadline. For incoming records, reject text above a documented size and consider a finite service quantifier.

Converting the number to int would produce 42 and lose the three-column spelling. That is right for arithmetic but wrong for reconstructing the exact identifier. Validation is also not authorisation: a tag with an allowed shape may name a service the caller cannot use.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. import re

    Load the standard-library matcher.

  2. match = pattern.fullmatch('api-042')

    Check the complete short fixture.

  3. print(match.group('service'), match.group('number'))

    Print api and the original three-digit spelling 042.

  4. print(pattern.fullmatch('prefix-api-042') is None)

    Print True because the extra separator breaks the shape.

The fullmatch contract rejects a prefixed identifier and the ASCII digit range is intentional. Named groups expose the two validated fields without relying on numeric group positions.

Predict before you run

Which exact number field is printed?

Validate an event identifierPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Try too few digits.

Try: Replace 'api-042' with 'api-42' and guard the group print with if match is not None.

The guarded print is skipped; a two-digit identifier is rejected.

Show the numeric alternative.

Try: Add print(int(match.group('number'))) after the original group print.

A new line prints 42 while the original display remains api 042.

Before you move on

Would 'API-042' pass this original pattern, and why?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

No. [a-z] permits lowercase ASCII letters only. Adding case-insensitive matching would be a deliberate change to the identifier contract.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
DETAILED WALKTHROUGH / NOT JUST A SUMMARY

Where this idea earns its place

Regular expressions are appropriate when a bounded textual shape is easier to specify as a pattern than as manual scanning. They are not a universal replacement for JSON, CSV, HTML or programming-language parsers. Start by stating whether the task validates a complete field, extracts a substring or replaces selected occurrences.

Follow the mechanism step by step

search may succeed anywhere in the input, while fullmatch requires the complete string to satisfy the pattern. Groups identify submatches and named groups make extraction less dependent on numeric positions. A raw Python string affects Python escaping; it does not disable the regular-expression engine's own syntax.

Work through a concrete application

For an identifier such as api-042, define allowed service characters and exactly three ASCII digits. Compile the fixed pattern, require fullmatch and read named groups only after checking that a match exists. Test a valid identifier, a prefixed identifier and a wrong-length suffix to show the difference between recognition and substring search.

Failure cases and misleading shortcuts

Unescaped metacharacters from user text can change a constructed pattern's meaning. Ambiguous nested repetition can take excessive time on near-matching input. Broad digit or whitespace classes may admit Unicode characters beyond an application's intended alphabet. A regex match also grants no authorization to act on the matched identifier.

Cost, ownership and alternatives

Bound input size before matching and choose patterns with understandable backtracking behaviour. Compilation can avoid repeatedly parsing a fixed expression, but does not make an unsafe expression safe. For simple fixed prefixes or delimiters, string operations may be clearer and have a simpler performance story.

Verify the contract

Test nonmatching near misses, empty input, an unexpected trailing newline and Unicode edge cases. Verify group meanings and replacement escaping separately from acceptance. If a security-sensitive pattern is complex enough that reviewers cannot reason about it, reduce its responsibility or use a maintained parser for the actual format.

Transfer question: How would you search for a literal user-provided string containing punctuation?

Use a normal string search when that suffices. If the larger task requires regex, escape the literal with re.escape before composing it into a trusted pattern, and retain input-size limits. Escaping a literal does not validate an arbitrary user-supplied regex.

RECALL BEFORE YOU SCROLL

Can you explain it?

Try from memory. Feedback stays on this page and does not award judged progress.

Which requires an entire string to match?
TRANSFER THE IDEA

Rebuild: Validate an event identifier

Without copying the worked code, reproduce its observable contract: The fullmatch contract rejects a prefixed identifier and the ASCII digit range is intentional. Named groups expose the two validated fields without relying on numeric group positions. Then change one boundary input and explain the result.

Your practice starterPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

MAKE THE RULE WORK ON NEW INPUTS

Guided practice and transfer

These are public local learning checks, not certified scores. Edited code is saved only with Save work and place. Run results are not stored as certified scores. Export useful unsaved work before leaving.

A short function primer before you begin

def names a reusable rule. The input names in parentheses are parameters. Indent its body; replace the starter's pass placeholder. The body runs when called, not when defined.

return hands a value back and ends that call. print only displays a value. The public assert checks call your function with fresh fixtures; a false condition raises AssertionError with its message.

Return a value, do not only print itPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

GUIDED PRACTICE

Guide: validate bounded event tags

Return whether one whole tag fits the stated ASCII shape.

The contract

  • Input is a string; accept one to eight lowercase ASCII letters, a hyphen and exactly three ASCII digits.
  • Return an actual bool. Empty, prefixed, suffixed and overlong values are False; do not strip whitespace.
  • Bound length before matching. Do not mutate or normalise the input.
Guide: validate bounded event tagsPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Inspect 6 public checks

Transparent local learning checks, not exhaustive or tamper-proof grading.

  1. normal bool
    r = valid_tag('api-042')
    assert type(r) is bool and r is True
  2. empty
    r = valid_tag('')
    assert type(r) is bool and r is False
  3. whole input
    r = valid_tag('x-api-042-y')
    assert type(r) is bool and r is False
  4. width boundary
    r = valid_tag('abcdefgh-999')
    assert type(r) is bool and r is True
    assert valid_tag('abcdefghi-999') is False
  5. ASCII and case
    r = valid_tag('api-٠٤٢')
    assert type(r) is bool and r is False
    assert valid_tag('API-042') is False
  6. unchanged repeated calls
    text = 'api-000'
    r = valid_tag(text)
    assert type(r) is bool and r is True
    assert valid_tag(text) is True and text == 'api-000'
    assert valid_tag('api-000 ') is False
    Why not use search or strip first?

    Both broaden the accepted input. The bounded fullmatch checks exactly the supplied string. Work is bounded by this fixed input cap; the result retains no mutable input.

    GUIDED PRACTICE

    Guide: count a literal fragment

    Count non-overlapping literal occurrences, including punctuation.

    The contract

    • Both arguments are strings, with text at most 128 characters and needle at most 16.
    • Return an integer count, not bool. Empty needle has defined count 0; matching is case-sensitive and non-overlapping.
    • Inputs are not modified. Use literal string operations or re.escape, never interpret needle as regex code.
    Guide: count a literal fragmentPYTHON 3

    Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

    Preparing the editor controls. Run and editing become available when this page is interactive.

    Browser Python limits

    Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

    Inspect 6 public checks

    Transparent local learning checks, not exhaustive or tamper-proof grading.

    1. literal dot
      r = literal_count('a.b axb a.b', 'a.b')
      assert type(r) is int and r == 2
    2. empty text
      r = literal_count('', 'x')
      assert type(r) is int and r == 0
    3. empty needle
      r = literal_count('abc', '')
      assert type(r) is int and r == 0
    4. nonoverlap
      r = literal_count('aaaaa', 'aa')
      assert type(r) is int and r == 2
    5. literal brackets and case
      r = literal_count('[x][x]X', '[x]')
      assert type(r) is int and r == 2
      assert literal_count('Xx', 'x') == 1
    6. input preservation
      text, needle = '++a++', '++'
      r = literal_count(text, needle)
      assert type(r) is int and r == 2
      assert (text, needle) == ('++a++', '++')
      assert literal_count(text, needle) == 2
      Why is str.count a good alternative to regex here?

      It already states the literal non-overlapping contract. No pattern compilation or escaping is needed. It scans the bounded string and returns an integer without creating shared mutable output.

      TRANSFER / TRY BEFORE OPENING HINTS

      Transfer: parse and range-check a quantity

      Change from yes/no tag validation to extracting a checked quantity record.

      The contract

      • Input is a string at most 64 characters. Valid form is one to eight lowercase ASCII letters, colon, one or two ASCII digits.
      • Return a fresh dict {'kind': str, 'count': int} only when count is 1 through 20 inclusive; otherwise return None.
      • Leading zeros are allowed but converted to an integer. Do not strip whitespace or mutate input; repeated valid calls return independent dictionaries.
      Transfer: parse and range-check a quantityPYTHON 3

      Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

      Preparing the editor controls. Run and editing become available when this page is interactive.

      Browser Python limits

      Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

      Inspect 6 public checks

      Transparent local learning checks, not exhaustive or tamper-proof grading.

      1. shape and types
        r = parse_quantity('box:04')
        assert type(r) is dict and r == {'kind': 'box', 'count': 4}
        assert type(r['kind']) is str and type(r['count']) is int
      2. empty rejection
        r = parse_quantity('a:1')
        assert type(r) is dict and r == {'kind': 'a', 'count': 1}
        assert parse_quantity('') is None
      3. range ends
        r = parse_quantity('box:20')
        assert type(r) is dict and r['count'] == 20
        assert parse_quantity('box:0') is None and parse_quantity('box:21') is None
      4. whole ASCII shape
        r = parse_quantity('x:02')
        assert type(r) is dict and r == {'kind': 'x', 'count': 2}
        assert all(parse_quantity(x) is None for x in [' x:2', 'x:2!', 'X:2', 'x:٢'])
      5. field width
        r = parse_quantity('abcdefgh:01')
        assert type(r) is dict and r['count'] == 1
        assert parse_quantity('abcdefghi:1') is None and parse_quantity('a:001') is None
      6. fresh ownership
        text = 'job:3'
        a = parse_quantity(text)
        b = parse_quantity(text)
        assert type(a) is dict and type(b) is dict and a == b == {'kind': 'job', 'count': 3}
        assert a is not b
        a['count'] = 99
        assert b['count'] == 3 and text == 'job:3'
        What changed beyond the guided validators?

        Success now produces an owned typed record, and syntax is insufficient: a numeric business range must also pass. The short fixed cap bounds matching work; one new dictionary is allocated per success.

        A GOOD PLACE TO PAUSE

        Core route complete.

        If you can explain the checkpoint and attempt the practice, move on. Come back for the deep dive when you want the why behind the how.

        Save your core reading milestone

        Pattern complexity is an input risk

        A safe matching boundary limits the work it accepts. Nested choices that can describe the same prefix may force a backtracking matcher to retry many paths.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        An import boundary may receive malformed near-matches as well as normal tags. A tiny pattern is not automatically cheap. Learn how to avoid ambiguous repetition rather than running a deliberately explosive example inside a browser.

        Words you will see

        Backtracking
        Trying earlier matching choices again after a later part fails.
        Ambiguity
        Multiple ways for repeated parts to cover the same input.
        Short-circuit
        Skipping the right side of and when the left side is false.

        Bound both accepted shape and attempted work

        The longest valid tag here has eight letters, one hyphen and three digits: twelve characters. valid first checks that inclusive cap. An overlong fixture returns False before fullmatch is called. The pattern also limits each field and separates them with a character neither field can consume.

        Nested overlapping repetition, such as a repeated variable-length group inside another repetition, can create many ways to divide a prefix. A failing suffix may trigger retries. Prefer a simple bounded shape and a parser for complex structure; a cap is defence in depth, not a universal proof about regex cost.

        Test rejection without creating a denial-of-service demonstration

        The 40-letter fixture is intentionally small and the guard rejects it immediately. api-04x fits the size cap but fails the digit rule. Separate tests for size and shape tell you which part of the boundary is working.

        Do not claim timing from one run. Total work also includes reading and allocating the input before this function. At an external boundary, enforce byte-size limits before decoding huge bodies. Python's standard re API does not provide a per-match timeout argument.

        The original example, step by step

        These steps explain the original code below. They do not change when you edit your own experiment.

        1. pattern = re.compile(r'[a-z]{1,8}-[0-9]{3}')

          Choose a finite, non-overlapping identifier shape.

        2. return len(text) <= 12 and pattern.fullmatch(text) is not None

          Reject too-long input before attempting the match.

        3. print(valid('a' * 40 + '-042'))

          Reject a bounded overlong demonstration.

        4. print(valid('api-04x'))

          Reject a short but malformed number.

        Nested ambiguous repetition can backtrack catastrophically on near-matches. Bound input length, avoid ambiguous patterns and test adversarial nonmatching strings. A regex is not safe just because its source is short.

        Predict before you run

        Does the forty-letter fixture reach fullmatch?

        Bound before matchingPYTHON 3

        Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

        Preparing the editor controls. Run and editing become available when this page is interactive.

        Browser Python limits

        Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

        Change one thing; explain the difference.

        Try the exact service limit.

        Try: Add print(valid('abcdefgh-007')).

        It prints True: eight letters plus four more characters fit both constraints.

        Try one letter too many.

        Try: Add print(valid('abcdefghi-007')).

        It prints False before matching because the input length is thirteen.

        Before you move on

        Is the twelve-character value 'abcdefgh-00x' accepted just because it fits the cap?

        Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

        Read a worked answer

        No. Size is necessary but insufficient. The final x fails the required three-digit field, so fullmatch returns None.

        This is a self-check, not a required quiz or a saved score. You can revisit any concept.

        Security and semantics

        Literal text and regex syntax are different languages. Escape a caller's literal fragment before embedding it in a regex, or avoid a regex when plain containment is enough.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        A user may search for a product label containing punctuation. Treating that label as pattern code changes its meaning and can introduce expensive patterns. Use string containment for simple literal search; escape when a literal must be combined with fixed pattern structure.

        Words you will see

        Metacharacter
        A character such as dot with special pattern meaning.
        Literal
        Text matched as itself rather than interpreted as instructions.
        Escaping
        Adding syntax that asks the matcher to treat special characters as ordinary text.

        See why the first result is wrong for a literal search

        In the first search, the dot accepts x. search stops at axb because that is the earliest match. The needle string is unchanged, but its interpretation is wrong for the intended literal task. re.escape builds pattern text that requires the dot itself.

        The escaped search skips axb and returns a.b. The final in expression simply checks whether the literal substring is present, so it is the clearer choice here. Escaping is useful when fixed regex structure, such as a bounded field boundary, surrounds a dynamic literal.

        Escaping has a precise scope

        re.escape prepares literal pattern text; it is not a general sanitizer and is not the correct tool for a substitution replacement string. It also does not authorise use of the matched record. Match APIs still need a clear policy for empty needles and maximum input sizes.

        For a fixed escaped pattern over a short input, reasoning is straightforward. Do not accept an arbitrary caller-supplied pattern merely because the caller meant a search term. The browser example uses only two small strings and performs no network or filesystem operations.

        The original example, step by step

        These steps explain the original code below. They do not change when you edit your own experiment.

        1. needle = 'a.b'

          The requested label contains a real dot.

        2. print(re.search(needle, text).group())

          Unescaped syntax matches axb first.

        3. escaped = re.escape(needle)

          Prepare a pattern for that literal label.

        4. print(re.search(escaped, text).group())

          Print the later literal a.b occurrence.

        Do not validate an entire email standard or parse nested programming syntax with an improvised regex. Distinguish validating an identifier from authorising the user associated with it. Escape user-provided literal text with re.escape when constructing a search.

        Predict before you run

        Why does the first line print axb?

        Search a literal punctuation markPYTHON 3

        Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

        Preparing the editor controls. Run and editing become available when this page is interactive.

        Browser Python limits

        Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

        Change one thing; explain the difference.

        Use a different wildcard match.

        Try: Set text = 'a-b a.b'.

        The first result becomes a-b; the escaped result stays a.b.

        Use only the literal tool.

        Try: Replace the two regex print calls with print(text.find(needle)).

        find reports position 4 for the original fixture and does not interpret punctuation.

        Before you move on

        If the fresh needle is '[ok]', should an unescaped regex mean the four-character label?

        Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

        Read a worked answer

        No. Brackets create a character class. Use '[ok]' in text or re.escape('[ok]') with a match operation to preserve the literal brackets.

        This is a self-check, not a required quiz or a saved score. You can revisit any concept.

        Make the explanation your own.

        Use Save work and place to store notes with your code. Unsaved edits stay in this course tab; export before leaving. Reading milestones remain separate.

        Take a versioned study copy

        Export this lesson's original theory, textual model explanations, worked examples, public exercise checks and local-runtime boundaries for reading/review. This is separate from exporting your private workspace: no learner code, notes, identity, saved place or results are included. Offline server/browser execution is not provided.

        Worked examples and explained concept checkpoints remain included. Reference answers for independent work are excluded unless you explicitly select them. A downloaded answer is not an earned pass.

        REFLECT, THEN CONTINUE

        Make this a milestone.

        Save a self-reported core reading milestone and confidence. Confidence 1-3 schedules a review when none is already set; higher confidence does not create a new review. This is not a code execution pass or proof of mastery. Deep-dive reading is optional and is not tracked separately yet.

        Your account

        Loading account...

        Sign in to save your work across devices.