The Pain Point First: Regex Is a Classic Case of "Great When You Write It, Clueless When It Breaks"
Regular expressions are probably one of the most contradictory tools in a programmer's daily work: write them correctly and you save dozens of lines of code; write them wrong and a single data cleaning job can silently pollute an entire table. Independent developers and small teams have especially complicated feelings about them—
- When you need one, you cram at the last minute, copy-paste an expression from search results, afraid to modify it or too lazy to;
- Ship it as long as it seems to run, until one day a batch of "looks like it matched but shouldn't have matched" data shows up in production logs;
- Want to verify it, but have no idea where to start constructing test cases, especially those nasty edge-case inputs.
So many people naturally think: let AI write the regex. That is indeed the right direction, but the right direction doesn't mean you're taking the right path.
Time for Counterexamples: Three Common Failure Patterns
Failure Pattern One: One-Sentence Requirements, Straight to the Answer
The most typical way of asking:
> Help me write a regex that matches phone numbers.
The AI will cooperatively produce ^1[3-9]\d{9}$, which looks perfect. But what is the definition of a "phone number" in your business? Should it support the +86 prefix? What if the user's input contains spaces or dashes in the middle? Should an 11-digit number starting with 12 be allowed? Until these ambiguities are resolved, any answer the AI gives is just "its guess at your requirements," not "your requirements."
Failure Pattern Two: Paste the Regex and Never Verify It
The AI returns a regex, you copy it, run it, see the first example match successfully, done. This is the most dangerous step—the traps of regex hide precisely beyond "the first example that runs." Wrong capture group numbers, greedy matching swallowing too much, changed ^/$ behavior in multiline mode—none of these problems show up on the first positive test case.
Failure Pattern Three: Testing Only Positive Cases
Even when people remember to test, they usually only test "strings that should match." But the real quality dividing line for regex is negative boundaries: strings that look right but shouldn't match, empty strings, extremely long inputs, special characters, Unicode characters. Verification that only tests positive cases is essentially no verification at all.
The Right Path: Make the AI Play Both Roles—Writer and Adversarial Tester
The correct process is to turn the AI from an "answer generator" into a "regex engineering collaborator." My current approach has four steps:
Step 1: Write the requirements as a spec, not a sentence. The source of the input, the variations the format allows, the forms explicitly rejected—write all of it out clearly. The more your requirements read like a test spec, the higher the quality of the regex the AI produces.
Step 2: Ask the AI to restate its understanding before giving an answer. Have the AI describe the matching rules in its own words and proactively list the ambiguities it's unsure about. This step alone can surface at least half of the requirement gaps in advance.
Step 3: Have the AI construct its own bidirectional test set of positive and negative cases. The key isn't whether the AI's regex is correct, but whether it can generate a set of boundary cases—ones that "should match" and "absolutely must not match": empty strings, interfering prefixes/suffixes, similar formats, extreme lengths. The AI is often much faster than humans at this step, because it has seen massive amounts of real-world dirty data patterns.
Step 4: Run verification in the target language environment. Regex dialect differences (Python's re, JS's RegExp, grep's BRE/ERE) are hidden landmines—verification must be done in the exact engine that will run it in production. The AI can directly generate test code in the corresponding language.
A Reusable Prompt Template
Use the following directly as a prompt, replacing the bracketed content:
你是一名正则表达式工程师。请按以下流程工作,不要跳步:
【需求描述】
- 匹配目标:[描述要匹配的内容,如"中国大陆手机号"]
- 输入来源:[数据来自哪里,如"用户在表单中手动输入"]
- 必须接受的格式:[列出所有合法变体,如"13800138000、+8613800138000"]
- 必须拒绝的格式:[列出明确非法的情况,如"11位但第二位是2、含空格"]
- 目标引擎:[运行环境,如"Python re 模块"]
【你的任务】
1. 先用你自己的话复述匹配规则,列出你仍然不确定的歧义点,等我确认后再继续。
2. 给出正则表达式,并逐段解释每个部分的含义。
3. 构造测试用例,分为四组:
a. 应匹配的标准用例(至少5个)
b. 应匹配的边界用例(前后有干扰文本、可选部分出现/不出现等,至少5个)
c. 不应匹配但形态相近的用例(至少8个,如多一位/少一位/错误前缀/非法字符)
d. 不应匹配的极端输入(空串、超长字符串、特殊字符、换行、全角字符)
4. 生成一段可直接运行的 [目标语言] 测试代码,逐一断言上述用例,输出通过/失败结果。
5. 指出这个正则的已知局限,以及哪些场景下它可能误判。Before and After Using AI
Before AI: Search the web for a regex → eyeball it for a couple of seconds → paste and ship → after things break, reverse-engineer the problem from dirty production data. A single rework starts at half a day, and even after fixing it you still feel uneasy—because you don't know where the next edge case will pop up.
After AI: Write a clear spec (10 minutes) → AI restates and confirms (one round of conversation) → receive the regex + bidirectional boundary test set + runnable test code (a few minutes) → run everything locally, ship once it's all green. The whole process takes under half an hour, and the test code it produces can stay in the project as regression tests. More importantly, the "uncertain points" the AI proactively raises often help me discover requirement details I hadn't thought through myself—something simply "searching for a regex" can never give you.
As for cost, the conversational versions of mainstream models are more than sufficient for this kind of task; you don't need a flagship model. As for which tier to pick and how much to spend, go by the official pricing page and calculate based on your own usage frequency.
Some Closing Advice
Regex is exactly the kind of "small but sharp" tool that benefits most from an AI-driven engineering process: spec first, AI restatement, bidirectional boundary testing, verification in the target engine. Miss any one of these four steps, and you'll get a production alert some late night. Save that prompt template above into your toolbox—next time you need a regex, make the AI your adversary first, then your author.
If you don't yet have a stable AI API channel, or want to flexibly switch between multiple models depending on the task type (a lightweight model for writing regex, a flagship for complex reasoning), you can try this model aggregation platform—register to get started: https://api.thistoken.ai/register
---
Tired of juggling provider integrations? Register at https://api.thistoken.ai/register and call every model through one base_url.
Хотите попробовать Token.AI?
Создайте API Key уровня проекта, включите каналы в консоли и настройте маршрутизацию, бюджеты и журналы аудита.
注册 ThisToken.AI 并获取 API Key