AI Hints
Home›NLP Tutorial›Practical Decisions
NLP · Lesson 74 of 106

Rules Still Win

When a pattern beats a model.

⏱ 2 min read▶ Video at 2:08:34🎓 Free
Watch this lesson in the NLP courseWatch on YouTube ↗Full NLP course

A team spends a week building a model to find order numbers. A simple pattern would have taken a minute. If something has a fixed format, you don't need AI. It's a good habit to ask this first.

Rules Still Win
From the video: Rules Still Win
  • A week on a model
  • A pattern takes a minute
  • Fixed formats don't need AI

Extraction by pattern

Order numbers, dates, money amounts, and email addresses all have fixed shapes. A small dictionary of patterns finds all of them. Run it. Four clean results, from one sentence, in microseconds, and for free. It never makes things up. These results can be passed to a language model as trusted facts, or be used to check what a model extracted. Rules and models work best together.

patterns.pypython
import re

PATTERNS = {
    "order": r"\b[A-Z]{2}\d{4}\b",
    "date": r"\b(?:\d{1,2} (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))\b",
    "amount": r"[$£€]\d+(?:\.\d{2})?",
    "email": r"[\w.]+@[\w.]+\.\w+",
}

text = "Order AB1234 from 3 Mar cost $18.50, please email sam@example.com"
for name, pattern in PATTERNS.items():
    print(f"{name:<7} {re.findall(pattern, text)}")
Output
order   ['AB1234']
date    ['3 Mar']
amount  ['$18.50']
email   ['sam@example.com']

Summary

Use patterns for shapes, and models for meaning. Which raises the biggest question of all. Which tool should you use?

Key takeaways
  • Fixed formats need patterns
  • Fast, free, and exact
  • Combine with models
Next up: Choosing the Right Tool — from a keyword to an LLM