Putting groups + alternation + replacement together
You now have everything for production-grade text transformation. Let's combine it on three real tasks.
Task 1: Normalize log timestamps
Logs from different sources use different timestamp formats: 2026-05-04T14:32:11Z, 04/May/2026 14:32:11, 14:32:11 04 May 2026. Pick one canonical format and convert all to it.
Strategy: write three patterns matching each input format with named groups, then sub each one to the canonical format with backreferences.
Task 2: CSV with awkward quoting
Real CSV is messy: Pippa,"3, going on 30",warm. The middle field has a comma INSIDE quotes. Pattern that handles both quoted and bare: (?:"([^"]*)"|([^,]*))(?:,|$). Capture each field with finditer.
Task 3: Markdown to HTML conversion (subset)
Convert **bold** to <strong>bold</strong>:
re.sub(r'\*\*([^*]+)\*\*', r'<strong>\1</strong>', text)
One line per Markdown construct. Real Markdown parsers exist for production; for ad-hoc rewrites, regex is faster.
The combined principle
- Describe the input shape with named groups.
- Use non-capturing groups for scoping.
- Use alternation for known variants.
- Use backreferences in replacement to reorder.
- Test with at least one adversarial input per pattern.
Five steps. They scale from one-line transforms to full log pipelines.