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
^: matches the beginning of the string\d{6}matches exactly six digits.(?:\d{4})?this non-capturing (non-capturing because of ?:) group matches exactly four digits. This group is optional.$: 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).