Loading...
Translate a small text format into a pattern, then choose whether the task needs a substring search or validation of the entire input.
What you'll be able to do
Suppose a laboratory sample identifier must contain exactly two uppercase ASCII letters, a hyphen and three ASCII digits. AB-007 is valid; A-007, AB-07 and AB-007X are not. A pattern for this contract is [A-Z]{2}-[0-9]{3}. Square brackets define allowed characters and braces specify the exact repetition count. The hyphen outside the class is a literal separator.
Use a raw Python string for patterns containing backslashes so that the regex engine receives them clearly. A period normally means any character except a newline, so a literal point needs escaping. Parentheses group parts of a pattern; an alternation such as (red|blue) selects a complete alternative. Explain the required language before choosing syntax, and avoid making a more general validator than the scenario needs.
re.search looks for a match anywhere in the text. re.match starts at the beginning but can still leave an unmatched suffix. re.fullmatch requires the whole string to satisfy the pattern. A validator should not accept AB-007X merely because its initial six characters form a valid identifier. The code uses fullmatch and converts the match object or None into an explicit Boolean result.
Character classes have scope. In Python’s default Unicode text patterns, \d can match decimal digits beyond ASCII. If an interface contract requires the characters 0 through 9, write [0-9]. Likewise, methods such as str.isalpha are not restricted to English ASCII letters. Do not claim that one convenient shorthand is equivalent to a narrower contract unless the flags and input domain establish that equivalence.
import re
sample_id = re.compile(r'[A-Z]{2}-[0-9]{3}')
def valid_sample_id(text):
return sample_id.fullmatch(text) is not None
for text in ('AB-007', 'A-007', 'AB-07', 'AB-007X', 'ab-007', 'AB-٠٠٧'):
print(valid_sample_id(text))
report = 'Accepted AB-007; rejected bad data; accepted QZ-120.'
print(sample_id.findall(report))Scroll horizontally to see the full code or table.Regex validates the specified text structure; it does not prove that an identifier exists in a database or that the person submitting it has permission to use it. Similarly, a date-shaped string can still describe an impossible calendar date. Follow structural parsing with semantic checks when the scenario needs them. Keep the raw input if audit or feedback needs to explain which part failed.
Test empty input, each missing or extra character, wrong case, wrong separator, leading/trailing text and a valid boundary-shaped example such as AA-000. Decide explicitly whether whitespace should be stripped before validation. This lesson’s function does not strip it, so " AB-007" fails. For extracted identifiers in prose, state whether adjacent letters are allowed; the simple findall example is extraction practice, not a universal token-boundary rule.
Attempt the task before opening its worked response. Record each change of state, explain the rule used, and check the result against the original requirements. Code examples labelled Python 3 use that language’s conventions; pseudocode states its own assumptions.
Common mistakes to avoid
Key takeaways
Test yourself
Answer a few questions, then review anything you missed.
Start with the quiz above to check the key ideas. You can also choose another topic from the practice library.