──────────────────────────────────────

22. The Message Sorting Desk · Recognise a Ticket Code

Apply a regular expression to validate an entire line.

Lesson files · lessons/text-automation/validate-with-regex

Before you start
- Read a line of text and choose between two messages.
- Use a test input near a rule’s boundary.

By the end
- Validate an entire ticket code with a fixed prefix and exactly four digits.
- Choose a failing example that would pass if a match could occur within a longer line.

Where you can use it
Check ticket codes pasted into a register and reject entries with extra text before looking them up.

A regular expression describes a text pattern. [A-Z] matches one uppercase ASCII letter, [0-9] matches one digit, and {2} means two repetitions. re.fullmatch requires the whole string to fit. Start with examples that should pass and nearly matching examples that should fail.

Predict
Does RP-007extra match the whole pattern?
- Yes.
- No.

Worked example (example.py)

import re
code = input().strip()
print(bool(re.fullmatch(r"[A-Z]{2}-[0-9]{3}", code)))


Example input
RP-007

Example result
True

Accept exactly SL- followed by four digits. Print Valid or Invalid.

Starter program (starter.py)

import re
code = input().strip()
print(bool(re.fullmatch(r"[A-Z]{2}-[0-9]{3}", code)))


Starter input
RP-007

Hint
Use r"SL-[0-9]{4}" and a branch around re.fullmatch.

Case 1. Try the sample
Input
SL-0042
Expected output
Valid

Case 2. Extra character
Input
SL-0042A
Expected output
Invalid

Stretch
Write a test for too few digits and one for a lowercase prefix.

Reflect
What would change if you used re.search instead of re.fullmatch?

Check your prediction
No. fullmatch requires every character in the cleaned input to be accounted for.
