Every sign-up test with a verification code reaches the same point: the email arrived, and now you need to get 482913 out of it. The first try is usually this:
const code = email.text.match(/\d{6}/)?.[0];
It works on the first email and breaks on the tenth. This post shows why, how to write a more reliable version, and how saci.cc hands you the code already extracted so you don't need either.
Why /\d{6}/ breaks
A real email has plenty of numbers besides the code:
- Order and ticket numbers: "Order #120394 · Your code is 482913". The regex picks the order, which comes first.
-
Prices, dates and times: "$149.90", "11/22/2026", "valid until 14:30". With
\d{4,8}, the year 2026 becomes a code. -
Links: the HTML has URLs like
/confirm?token=839201&uid=1002931. Run on the HTML, the regex finds numbers inside links. -
CSS and colors:
#120394in astylehas six digits. - Other formats: "482-913", "482 913" or "K7P2QX". A six-digits-in-a-row regex misses all of them.
- Phone numbers and zip codes in the footer.
And when it's wrong, it's wrong quietly: the test types the wrong number, the app refuses it, and the failure looks like a sign-up bug.
Look for the word, not just the number
What sets the code apart from the other numbers is the text around it: "code", "verification", "password", "OTP". A more reliable approach:
- Use the email's text, not the HTML, and blank out links before searching.
- Find candidates: 4 to 8 digits, or
123-456and123 456, not stuck to other letters,#,$or slashes. - Drop years and numbers right after "order", "#", "$", "invoice" and the like.
- Keep the candidate closest to a word like "code", up to about 60 characters before or 40 after.
In TypeScript, a lean version:
// Words that usually sit near the code, in English and Portuguese
const KEYWORDS = /(c[oó]digo|code|otp|pin|verifica\w*|confirma\w*|senha|password|token)/gi;
// Numbers right after these are orders, invoices or prices
const NOT_A_CODE_BEFORE = /(#|n[ºo°.]\s*|pedido|order|invoice|fatura|r\$|\$)\s*:?\s*$/i;
const CANDIDATE = /(?<![\w#$.\/-])(\d{3}[- ]\d{3}|\d{4,8})(?![\w\/%-])/g;
function findCode(text: string): string | null {
const clean = text.replace(/https?:\/\/\S+/g, " ");
let best: { code: string; distance: number } | null = null;
for (const match of clean.matchAll(CANDIDATE)) {
const start = match.index;
const end = start + match[1].length;
const before = clean.slice(Math.max(0, start - 60), start);
const after = clean.slice(end, end + 40);
if (/^(19|20)\d{2}$/.test(match[1]) || NOT_A_CODE_BEFORE.test(before)) continue;
const last = [...before.matchAll(KEYWORDS)].at(-1);
const next = after.search(KEYWORDS);
const distance = Math.min(
last ? before.length - (last.index + last[0].length) : Infinity,
next >= 0 ? next : Infinity,
);
if (distance === Infinity) continue;
if (!best || distance < best.distance) best = { code: match[1].replace(/[- ]/g, ""), distance };
}
// null when no number is near any word: better to fail than type the wrong number
return best?.code ?? null;
}
It handles most cases, but it's worth knowing what it misses: codes with letters, words in other languages, accents, and emails that say "use the number below" with the code three lines later.
On saci.cc, the code comes ready
saci.cc does this search when the email arrives, with a longer word list in English, Portuguese and Spanish, codes with letters like K7P2QX, prefixes like Google's G-482913, and the exceptions for orders, prices, phone numbers and years. If the code is in the subject, it's found there. The result shows up everywhere:
-
In the API: the
verificationCodefield comes in the inbox list and in each email, with the code ornull. "482-913" comes as482913, ready to type. -
In the npm package:
waitForCode()waits for the email and returns just the code. -
In MCP: the
get_verification_codetool does the same for AI agents. - On the site and in the extension: a button copies the code without opening the email.
import { createInbox } from "saci.cc";
const inbox = await createInbox();
// ...
// Waits for the email and returns just the code
const code = await inbox.waitForCode({ from: "your-app.com" });
// Or the whole email, with the code and link already extracted
const email = await inbox.waitForEmail({ subject: /code|código/i });
console.log(email.verificationCode, email.verificationLink);
If your app sends a "Confirm email" button instead of a code, the verificationLink field and waitForLink() do the same with the link. The post on confirmation links explains which links count.
When the code isn't found
If verificationCode is null on an email that has a code, it's usually because no word is near it. Two ways out:
- Improve the email: "Your verification code is 482913" helps saci.cc, and also people reading the email with a screen reader.
- Read the email's
textwithinbox.waitForEmail()and use your own regex, anchored on your template's fixed text.
And send feedback to oi@saci.cc or through the API with the email's text: cases like that become tests and improve the search for everyone.
In short
-
/\d{6}/picks up orders, years, prices and numbers in links, and is wrong without warning. - Look for the number closest to a word like "code", in the text with links removed, and drop years and orders.
- On saci.cc, use
verificationCode,waitForCode()orget_verification_codeand skip all that.
I build saci.cc, temporary email inboxes for end-to-end tests and AI agents. The npm package is saci.cc and the client is open source on GitHub.
Top comments (7)
One more way this goes wrong quietly: picking the right number from the wrong email. If the test hits resend, or a retry reuses the inbox, the newest email might not be the one you just triggered. Recording a timestamp just before the action that sends the code, and only accepting emails received after it, closes that gap. When the app under test is your own, I'd also anchor on your template's fixed sentence first and keep the keyword search as the fallback, since a template change then fails loudly in one place. Does
waitForCodefilter by received time, or just take the latest match?Good point, and it's the failure I'd worry about most with reused inboxes or a "resend code" step.
waitForCode()takes anafteroption for exactly that. Without it, it also looks at emails already in the inbox (newest first) and returns the first one with a code, so a reused inbox can hand you a stale one. With it, only emails received after that moment count:One caveat:
receivedAtcomes from the server, so if the test machine's clock runs ahead, a tightaftercould skip the right email. Taking the timestamp a second or two early avoids that. A fresh inbox per test sidesteps the whole thing, since inboxes are cheap.And I agree on anchoring to your own template. When you own the email,
inbox.waitForEmail({ after })plus a regex on your fixed sentence is the strictest option, and a template change breaks one obvious assertion instead of quietly matching something else. The keyword search is mainly for emails you don't control, like third-party sign-ups in agent flows.The part of your post I keep turning over is "when it's wrong, it's wrong quietly" — the test types the wrong number and the failure looks like a sign-up bug rather than a bad matcher. I hit the identical shape this week on the other side of the pipe: deciding whether an HTTP request came from a person. My first instinct was the equivalent of
\d{6}, i.e. filter on the user agent, and it looked like it worked because the obvious strings (GPTBot, SemrushBot, YandexBot) matched and I could point at a number. Then I counted properly: of 25,542 requests to my click-tracking redirect in 14 days, only 90 named a bot in the user agent. The other 25,452 were plausible Chrome strings distributed over 66 different Chrome major versions. A UA filter is a six-digit regex over the whole web — it catches the case that announces itself and silently mislabels everything else, and because the surviving count still looks like a plausible traffic number, nothing ever throws.Your "use the word, not just the number" is exactly the fix, just applied to a different column: the field that carries intent is the one adjacent to the event, not the event itself. For me that was the referrer — 54% of those requests had none, and 17% had a referrer that cannot exist for a browser, which is a crawler resolving the target site's relative asset paths against my own redirect URL. Those requests were clicks in my database and machine noise in the log, and only one of the two interpretations leaves a receipt.
Two things I am taking from your post specifically. First, your point about decoys — order numbers, prices,
#120394in CSS — is a negative control, and I have no such thing anywhere in my measurement pipeline. The cheap version for me: fire one request with an empty referrer and one with a real page referrer, and assert the report separates them. A check that cannot fail on a known-bad input is not a check. Second, you extract the code by looking for the label word instead of trusting position; I have been trusting position in the opposite sense — my indexability rule treats a non-zero click count as "this listing is worth publishing", so 61 pages with no written copy, no view counts and no vendor claim ended up in the sitemap because a bot reached a redirect. Same bug you described: a matcher that grabs the first thing shaped like the signal, then feeds it straight into a decision.That’s a great parallel, and a scarier version of the same bug: with a verification code the test eventually fails, but a bot count that looks like plausible traffic never does.
The negative control is the part I’d steal back. In the post the decoys (order numbers, #120394 in CSS) are just examples of what goes wrong, but they work better as fixtures: an email with a code and a few six-digit decoys, asserting the matcher picks the right one. Same idea as your empty-referrer request: if the check can’t fail on a known-bad input, it isn’t checking anything.
And “a matcher that grabs the first thing shaped like the signal, then feeds it straight into a decision” is a better one-line summary of the post than the one I wrote.
A regex that grabs the first six digits takes #120394 instead of the code, and the test fails without saying why. Anchoring on the word code keeps that quiet failure out of the suite.
Exactly, the quiet part is what hurts: the test types a wrong code and the failure looks like a sign-up bug. One more case that bites even with the keyword search: an inbox that already has an older code, from a resend or a retry. Passing after: new Date() right before the action that sends the email keeps the stale one out.
the stale code already sitting in the inbox is the case that bites. new Date() right before the send keeps it out.