Regex Time, Part 3

Dec 08, 2009

How to retrieve a six (6) or ten (10) fixed-length digits string?

Test Cases

This kind of string should match our pattern:

  • a string of six (6) and only six (6) digits
  • a string of ten (10) and only ten (10) digits

All other strings should not match our pattern.

The Regular Expression Pattern

^\d{6}(?:\d{4})?$

The explanation

  1. ^: matches the beginning of the string
  2. \d{6} matches exactly six digits.
  3. (?:\d{4})? this non-capturing (non-capturing because of ?:) group matches exactly four digits. This group is optional.
  4. $: matches the end of the string

So, this regular expression could be read as:
Match a string of exactly six (6) digits which could be optionally followed by a string of exactly four (4) digits.
In conclusion, this regex will match a six (6) digits string or a ten (10) digits string (6 required digits + 4 optional digits).

Post a comment

Spam Protection by WP-SpamFree

Main Navigation

I am (not?) a Robot!

Recent Comments

Search

Subscribe and login