Why Your OTP Regex Keeps Breaking (and the API-Based Fix)
Developer
By the zephbox teamPublished Updated 5 min read
How we write these: product details are checked against the current zephbox API and site behavior on the date shown. Spotted a mistake? Tell us and we correct it (editorial policy).
A hand-written OTP regex breaks because verification emails are not a format; they are a free-for-all written by whoever built each service's template. Digits-only is the easy case. Real mail also contains order numbers, years, CSS values, tracking IDs, spaced or dashed codes and alphanumeric codes, and every one of those either gives you a false match or no match at all. The fix is not a cleverer regex, it is knowing exactly which cases your extraction covers and failing loudly on the rest.
The five ways a verification regex fails
| Failure | What the email contains (example) | What a naive \d{6} does |
|---|---|---|
| Wrong number | "Order 482913 confirmed. Your code is 107265." | Returns 482913, the first six-digit run, and the test then fails on a code that was never wrong in the app. |
| Wrong length | "Your code is 4817" | No match. Many services use 4, 5 or 8 digits. |
| Formatted code | "Your code: 482 917" or "482-917" | No match, because the digits are split by a space or dash. |
| Alphanumeric code | "Enter K7Q2XD" | No match at all; there are no digits to find. |
| Link instead of code | "Click here to verify" with a long tokenised URL | No match, and a bare digit run inside the URL can produce a false one. |
The rows above are illustrative examples, not captured emails. They are the patterns to put in your own test fixtures before trusting any extractor, yours or ours.
The two bad fixes
The first instinct is to loosen the pattern, for example matching any 4-8 digit run. That cures "wrong length" and makes "wrong number" worse. The second instinct is to anchor on wording: look for "your code is" and take the digits after it. That cures "wrong number" and breaks the moment a template says "use this to confirm" or localises the sentence. Each fix trades one failure for another, and each service you add to the test suite needs its own tuning. That is the maintenance cost: it recurs whenever a third party edits an email template, and you only find out when a test goes red for no visible reason.
What a combined approach looks like
The approach that holds up is layered: prefer a number near a verification phrase, look in the subject first, then fall back to a looser rule, and always keep the raw message available when nothing matched. That is how the zephbox OTP endpoint works. The behavior below is taken from the extraction code, not from marketing copy:
- It looks for a 4 to 8 digit number that is not part of a longer digit run, so a 14-digit tracking number is not sliced into a code.
- It first looks for anchor phrases such as "verification code", "security code", "one-time", "login code", "OTP", "passcode", "code is" or "enter the code", and takes the number within roughly 60 characters of one. The subject line is checked first, then the plain-text body, then the HTML body with tags stripped.
- If no anchor matches anywhere, it falls back to the first standalone 4-8 digit run in the plain-text body only. HTML is deliberately excluded from this fallback because stripped markup contains stray digit runs.
- For links it looks for anchor words like "verify", "confirm", "activate", "magic link", "sign in", "reset your password" or "complete your sign-up" within about 200 characters of an
http(s)URL, checking HTML first because that is where the realhreflives, and falls back to the first link found. - It scans the 10 most recent messages and returns the newest one that has a code or link, so a promotional email that arrives after the real OTP does not hide it. If none of the ten match, it returns the newest message with
codeandlinkset tonullrather than an error, so you can read the raw message.
What it still cannot do
Being honest about the limits is the useful part. Based on the rules above, the endpoint does not return:
- Alphanumeric codes such as
K7Q2XD; only digit codes of 4 to 8 digits are extracted. - Codes split by spaces or dashes, for example
482 917, because each fragment is shorter than four digits. - Codes in an image or an attachment.
In those cases the response still gives you the message id, subject, sender and time, and the full message is available from the messages endpoint, so a small custom parser for that one service is all you need, not a general one.
A defensive pattern for your tests
resp = requests.get(f"{BASE}/aliases/{alias}/wait-for-otp/", params={"timeout": 20}, headers=H, timeout=25)
resp.raise_for_status() # 408 means no mail arrived in time
data = resp.json()
if data["code"] is None and data["link"] is None:
# Mail arrived but nothing matched: read it, do not guess.
msgs = requests.get(f"{BASE}/aliases/{alias}/messages/", headers=H, timeout=10).json()
raise AssertionError(f"No code found in: {msgs[0]['subject']!r}")Two habits make any extractor safer. Assert that the sender is the service you expect, so a stray message cannot satisfy the test. And assert the outcome that matters, an activated account, rather than that "a code was found".
When to keep your own regex
If you only ever verify against one service whose template you control, such as your own product, a small regex you own is reasonable and has no network dependency. The case for server-side extraction is a suite that touches many third-party templates, where the cost of the long tail is the problem. Details of the endpoint are in the API documentation; a worked suite is in signup testing with the Python SDK, and the push-based alternative to waiting is covered in webhooks vs. polling. API access requires a Full Access plan.
Frequently asked questions
Does the extractor return codes longer than 8 digits?
No. It looks for 4 to 8 digit numbers that are not part of a longer run of digits, so longer numbers such as tracking IDs are ignored.
What happens when no code is found?
If mail has arrived but nothing matches, the response still includes the message details with code and link set to null. If no mail has arrived at all, the OTP endpoint returns 404 and the wait endpoint returns 408 after its timeout.
Which message is used when several arrive?
The newest message among the 10 most recent that contains an extractable code or link. If none does, the newest message is returned with empty code and link.
Gmail & Outlook Temp Mail That Services Can't Block
95%+ acceptance rate for Facebook, Instagram, Netflix & OTP signups.
Try zephbox Premium →