Advanced·22 min·0/47 done

Python RegEx

Search, findall, groups, and substitution with the re module.

Why it matters: Extract JSON from LLM replies, parse logs, and redact emails before prompts leave your system.

Basics

re.search and findall

Import re, then:

  • re.search - first match anywhere
  • re.findall - every match as a list
  • re.sub - replace
  • re.compile - compile once, reuse

Always write patterns as raw strings: r"\d+". A match object is truthy, so if re.search(...): works.

Tiny example

Find digits in a short log line.

import re
print(re.findall(r"\d+", "latency_ms=120"))

Basics

Pattern Basics

Useful pieces:

  • \d digit, \w word char, \s whitespace
  • * + ? for counts
  • ( ... ) capture group
  • .*? lazy match (stops early)

Quantifiers are greedy by default. Use ? after * or + when extracting between markers.

Tiny example

Use a lazy match between two markers.

import re
text = "<a>one</a><a>two</a>"
print(re.findall(r"<a>(.*?)</a>", text))

Basics

When Not to Use RegEx

Do not parse nested JSON or HTML with regex. Use json.loads or an HTML parser.

Compile patterns used inside loops with re.compile.

Keep patterns simple. Nested quantifiers can become very slow.

Tiny example

Prefer json.loads for nested JSON.

import json
print(json.loads('{"score": 0.9}')["score"])

Then AI / ML

AI / ML examples

Same idea, used in real AI work. Press Try in lab to run it.

AI / ML example

AI / ML: extract JSON from a reply

Find the first {...} block, then parse it.

In AI / ML: Structured-output helpers search for JSON before json.loads.

example.py

Python

import json
import re

reply = 'Sure! {"sentiment": "positive", "confidence": 0.92} done.'
match = re.search(r"\{.*\}", reply)
data = json.loads(match.group())
print(data["confidence"])

AI / ML example 2

AI / ML: redact emails

Replace emails before sending text to a model.

In AI / ML: Pre-LLM redaction replaces emails and phones in prompts.

example.py

Python

import re

text = "Contact priya@example.com today."
clean = re.sub(r"[\w.+-]+@[\w-]+\.[\w.]+", "[EMAIL]", text)
print(clean)

Takeaways

  • 1Write patterns as raw strings; compile patterns used in loops.
  • 2Use .*? when extracting between markers.
  • 3Never parse nested JSON or HTML with regex.
Certificate