Regex (regular expression)
Also: 正則表達式 · 正規表示式 · regular expression · 模式匹配 · regex 是什麼
A notation for describing what a piece of text looks like, used to find or validate matching fragments inside larger text.
When you will meet it
AI tools use regex for two jobs: pulling the part you want out of a model's long reply, and checking that an input has the right shape. You will meet it in custom filter rules, in an agent's parsing code, and inside some error messages. Without it your only move is to paste the whole thing at an AI — and the regex it hands back usually works only on the inputs it happened to imagine.
An analogy
Like the description on a wanted poster: '175 to 180 cm tall, scar on the left cheek'. The more precise the description, the fewer false matches — but the description cannot tell you whether such a person exists. When nothing matches, you cannot tell 'genuinely none' apart from 'I wrote the description wrong'.
Minimal example
import re
line = "訂單 ORD-20260930 已完成,金額 1280 元"
m = re.search(r"ORD-\d+", line)
print(m.group(0) if m else "沒找到") # → ORD-20260930
print(re.findall(r"\d+", line)) # → ['20260930', '1280']\d means 'one digit' and + means 'one or more', so ORD-\d+ reads as 'ORD- followed by a run of digits'. Note that the second line also captured the amount — regex recognises shape, not meaning.
What people get wrong
- Using regex to parse structured output such as a model's JSON reply. JSON has proper parsers; regex silently extracts the wrong thing when it meets nesting, escape characters or newlines, and never complains. The fix is to make the model use structured output or tool calling.
- Assuming 'no match' means 'not present in the data'. Far more often the format is off by one space, differs in case, or mixes full-width and half-width characters. Print the pattern and try it against real data to find out which it is.
Related terms
Next
- Function Calling Basics: Making the LLM Actually Use Tools26 minChinese only
- Build Your First AI Workflow Without Writing Code12 minChinese only