Verbose patterns

re.X for a receipt parser.

re.X lets you break a pattern across lines and add comments. Spaces in the pattern are ignored unless escaped.

Goal

Parse a receipt line with a readable pattern.

import re
pat = re.compile(r"""
    (?P<city>\w+)
    \s+kiosk\s+
    units=(?P<units>\d+)
    \s+price=(?P<price>[\d.]+)
""", re.X)
print(pat.search("Nairobi kiosk units=12 price=10.50").groupdict())
import re
pat = re.compile(r"""(?P<date>\d{4}-\d{2}-\d{2})\s+(?P<city>\w+)\s+(?P<kes>[\d.]+)""", re.X)
print(pat.search("2026-01-12 Nairobi 126.0").groupdict())
import re
# Without re.X a space is literal.
print(bool(re.fullmatch(r"Nairobi 12", "Nairobi 12")))
print(bool(re.fullmatch(r"Nairobi 12", "Nairobi12")))
import re
pat = re.compile(r"Nairobi[ ]12", re.X)  # escaped space
print(bool(pat.fullmatch("Nairobi 12")))