← Back to Python, page 3

python-0049 · Medium mid

Use regular expressions to extract and validate data, and explain greedy versus lazy matching.

re.search finds the first match anywhere, re.fullmatch requires the whole string to match, and findall or finditer return all matches, with named groups keeping results readable. Quantifiers are greedy by default and match as much as possible; adding ? makes them lazy. Compile patterns used repeatedly and prefer raw strings.

Full answer
python
import re
log = "2026-12-04 10:15 ERROR order=104 user=asha; 2026-12-04 10:20 INFO order=105 user=ben"
pat = re.compile(r"(?P<time>\d{2}:\d{2}) (?P<level>[A-Z]+) order=(?P<order>\d+)")
print([m.groupdict() for m in pat.finditer(log)])
html = "<b>bold</b><i>it</i>"
print(re.findall(r"<.+>", html), re.findall(r"<.+?>", html))
pin = re.compile(r"[1-9]\d{5}")
print(bool(pin.search("PIN 4110016")), bool(pin.fullmatch("4110016")), bool(pin.fullmatch("411001")))
print(re.sub(r"\s+", " ", "too    many   spaces"))

Output:

text
[{'time': '10:15', 'level': 'ERROR', 'order': '104'}, {'time': '10:20', 'level': 'INFO', 'order': '105'}]
['<b>bold</b><i>it</i>'] ['<b>', '</b>', '<i>', '</i>']
True False True
too many spaces

Named groups give dictionaries per match, which is clearer than numbered groups. The greedy <.+> swallows the whole string from the first < to the last >, while the lazy <.+?> stops at each tag. search finds a six-digit run inside the seven-digit text, but fullmatch rejects it, which is why validation should use fullmatch (or anchors). Regex is good for structured text such as logs; for HTML or JSON, use a real parser.

python
import re
log = "2026-12-04 10:15 ERROR order=104 user=asha; 2026-12-04 10:20 INFO order=105 user=ben"
pat = re.compile(r"(?P<time>\d{2}:\d{2}) (?P<level>[A-Z]+) order=(?P<order>\d+)")
print([m.groupdict() for m in pat.finditer(log)])
html = "<b>bold</b><i>it</i>"
print(re.findall(r"<.+>", html), re.findall(r"<.+?>", html))
pin = re.compile(r"[1-9]\d{5}")
print(bool(pin.search("PIN 4110016")), bool(pin.fullmatch("4110016")), bool(pin.fullmatch("411001")))
print(re.sub(r"\s+", " ", "too    many   spaces"))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • search, fullmatch, findall, finditer
  • Named groups improve readability
  • Greedy versus lazy quantifiers
  • Use fullmatch for validation
  • Use parsers for HTML and JSON

Common mistakes

  • Validating with search and partial matches
  • Parsing HTML with regex

Follow-ups

  • How would you match an email address reasonably?
  • What does re.VERBOSE allow?

Tips

  • Show greedy and lazy side by side