Regular Expressions · 19 min

Match and validate text

Use raw strings, character classes, quantifiers, and whole-string matching.

Jump to the automation lab

re.search() can match anywhere. re.match() starts at the beginning. Use re.fullmatch() when an entire field must follow a rule. The anchors ^ and $ describe boundaries, with additional behavior in multiline mode.

[A-Z] describes one capital letter, [0-9]{3} describes exactly three ASCII digits, and + means one or more. * means zero or more, while ? makes the previous item optional. A dot matches almost any character and \. matches a literal period.

Use a raw Python string such as r"\d+" so that the regex engine sees the backslash. In Unicode text, \d includes digits beyond ASCII. Use [0-9] when the format requires ASCII.

Follow the example

Read two uppercase letters.

Run the example and practice

Replace the partial match with whole-string validation. Keep the existing format and sample inputs.

Target output

True
False
False
False
Show a hint

The pattern already specifies the format. Change the re function used to apply it.

Output

Ready

Run your code to see the output here.

Check output also tests your code with additional cases.

The first run downloads Python. Code runs in your browser. Progress and drafts are stored on this device.

Show one solution
import re

def valid_ticket(text):
    return re.fullmatch(r"[A-Z]{2}-[0-9]{3}", text) is not None

for ticket in ["AB-042", "copy AB-042", "AB-42", "AB-042Z"]:
    print(valid_ticket(ticket))

Automation lab

Check names before importing purchase orders

A shared folder contains other documents. Only import names that match the required purchase-order format.

Output

Ready

Run the example to see the output here.

Add a name with an uppercase extension. Use re.IGNORECASE if names should ignore letter case.

Further reading in Automate the Boring Stuff with Python by Al Sweigart