Regular Expressions · 20 min

Extract fields with capture groups

Read groups from a match and handle records that do not match.

Jump to the automation lab

Parentheses capture part of a match. group(0) is the entire match and group(1) is the first capture. Use (?P<name>...) to name a field or (?:...) to group alternatives without capturing them.

A match object lets you read only the parts you need. Check for None before calling group(). In a monitoring line, regex can locate a field even when a timestamp or label comes first.

re.IGNORECASE ignores case while matching. After extracting a count, use int() to get a number. A format match alone does not establish that the value makes sense for the program.

Follow the example

The timestamp is unrelated to the field being extracted.

Run the example and practice

Return a pair containing the lowercase zone and the integer count. Keep returning None when no field matches.

Target output

('bay', 12)
None
('dock', 4)
Show a hint

Read the zone with match.group("zone").lower() and return it alongside the count.

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 extract_count(line):
    match = re.search(r"(?P<zone>bay|dock)=(?P<count>[0-9]+)", line, re.IGNORECASE)
    if match is None:
        return None
    return match.group("zone").lower(), int(match.group("count"))

for line in ["09:30 BAY=12", "no reading", "dock=4"]:
    print(extract_count(line))

Automation lab

Extract shelf codes from stock notes

Stock notes mix free text with structured shelf codes. Use named groups to pull the aisle and bin into separate fields.

Output

Ready

Run the example to see the output here.

Add a third shelf code and check that an incomplete code is skipped.

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