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 spacesNamed 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