PatternRegex

Match a 6-digit OTP

Pull a 6-digit one-time password out of an SMS or email body using a word-boundary match, without grabbing part of a longer number.

Last updated

Patterng
\b\d{6}\b
Open in Regex Tester & Builder

Matches

  • Your OTP is 482913 today
  • Reference code: 100200 expires soon

Doesn’t match

  • 12345
  • 1234567
  • OTP is 12

Why it’s written this way

\d{6} is the core of it: exactly six digits, no more and no fewer. Wrapping it in \b...\b — word boundaries — stops it from matching the middle of a longer run of digits, like the '482913' buried inside a 10-digit phone number.

It's deliberately left unanchored: an OTP arrives inside a sentence ('Your code is 482913'), not as the entire string, so ^ and $ would never match real SMS or email text.

Edge cases to know

  • Any six-digit number matches — an order ID, a PIN, or a slice of a longer reference number triggers a false positive just as easily as a real OTP.
  • It can't tell a code apart from surrounding digits split by a non-word character, like '482-913' — that reads as two separate 3-digit runs, not one 6-digit code.
  • Extracting an OTP from message text is one thing; logging or storing what you extract is another — treat matched codes as sensitive and keep them out of logs and analytics.

Related in Patterns