Read a regular expression as a sequence of small matching rules.
How It Works
A pattern such as ^[A-Z]{2}-\d{3}$ has anchors for the whole input, a two-letter character class, a literal hyphen and exactly three decimal digits. Interpret each component before combining it with a more complicated pattern. Raw string literals keep backslashes readable.
Regex \d matches Unicode decimal digits by default; use re.ASCII or [0-9] if only ASCII digits are allowed.
Step-by-Step Example
import re
pattern = re.compile(r"^[A-Z]{2}-\d{3}$")
for value in ["AB-123", "A-123", "AB-12X"]:
print(value, bool(pattern.fullmatch(value)))
Understanding the Example
- The expression 're.compile(r"^[A-Z]{2}-\\d{3}$")' supplies the value stored as 'pattern'. This value is then used or checked by the later statements.
- The for loop processes one item per iteration rather than requiring a separate statement for each value.
A successful run of this example prints the following output:
AB-123 True
A-123 False
AB-12X False
Where This Fits in a Real Program
Start by writing down examples that should match and examples that must fail. Check whether you need to locate a substring, match a prefix or validate an entire field; these are different operations. Unicode and escape sequences can also change which characters are matched, so test accented text and empty input.
Practice: Try It Yourself
Adjust the pattern to accept three letters and four digits, then test both correct and incorrect strings.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Confusing square brackets (character classes) with parentheses (groups).
- Using re.search() for whole-string validation and accidentally accepting extra characters.
Key Takeaways
- Read a regular expression as a sequence of small matching rules.
- A pattern such as ^[A-Z]{2}-\d{3}$ has anchors for the whole input, a two-letter character class, a literal hyphen and exactly three decimal digits.
- Regex \d matches Unicode decimal digits by default; use re.ASCII or [0-9] if only ASCII digits are allowed.