Validate a simple identifier by matching the complete value.
How It Works
A deliberately narrow identifier might require two ASCII letters, a hyphen and exactly four digits. fullmatch() prevents additional prefix or suffix text from being silently accepted. A regex can enforce syntax, not determine whether an identifier truly exists.
For security-sensitive identifiers, use explicit ASCII character classes if Unicode lookalikes must be rejected.
Step-by-Step Example
import re
identifier_pattern = re.compile(r"[A-Z]{2}-[0-9]{4}")
for item in ["AB-2026", "AB-26", "AB-2026 extra"]:
print(item, bool(identifier_pattern.fullmatch(item)))
Understanding the Example
- The expression 're.compile(r"[A-Z]{2}-[0-9]{4}")' supplies the value stored as 'identifier_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-2026 True
AB-26 False
AB-2026 extra False
Where This Fits in a Real Program
For event timestamps, distinguish the displayed local clock from the instant that it represents. Store or exchange an unambiguous aware value, then convert it when displaying it to a user. For repeated calendar appointments, use a geographic timezone so daylight-saving rules are not lost.
Practice: Try It Yourself
Extend the pattern to accept lowercase letters using re.IGNORECASE and compare behavior.
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
- Using re.search() for validation and accepting an otherwise valid substring inside invalid text.
- Confusing pattern validity with verification against a database of real identifiers.
Key Takeaways
- Validate a simple identifier by matching the complete value.
- A deliberately narrow identifier might require two ASCII letters, a hyphen and exactly four digits.
- For security-sensitive identifiers, use explicit ASCII character classes if Unicode lookalikes must be rejected.