Useful Regular Expression Patterns


Phone Numbers:

  • simple match that allows dashes as separators:
    ^\d{3}-\d{3}-\d{4}$
  • allows periods, dashes or spaces as separators:
    ^(\(\d{3}\)|\d{3})[\s\.-]?\d{3}[\s\.-]?\d{4}$
  • Matches to to the North American Numbering Plan (2009):
    ^(\([2-9][0-8]\d\)|[2-9][0-8]\d)[\s\.-]?[2-9]\d{2}[\s\.-]?\d{4}$

Postal Codes:

  • simple match:
    ^([A-Z]\d[A-Z])\ {0,1}(\d[A-Z]\d)$
  • allows unused “W” and “Z” as first characters:
    ^([ABCEGHJKLMNPRSTVWXYZ]\d[ABCEGHJKLMNPRSTVWXYZ])\ (\d[ABCEGHJKLMNPRSTVWXYZ]\d)$
  • 2009 rules:
    ^[A-CEGHJ-NPR-TVXY]\d[A-CEGHJ-NPR-TV-Z][- /]?\d[A-CEGHJ-NPR-TV-Z]\d$

U.S. Zip Codes:

  • Allows 5 and 5+4 zip codes:
    ^[0-9]{5}([- /]?[0-9]{4})?$

Roman Numerals:

  • Unlike the ones I found all over the internet, this one actually works (up to 3999):
    ^(M{0,3})((D?C{0,3})|C[DM])((L?X{0,3})|X[LC])((V?I{0,3})|I[VX])$

Reading CSV:

  • honours quoted strings:
    ^(?:([^",]+))?(?=,)|(?<=,)(?:[^",]*)?(?=[,$])|((?<=")[^"(\s*,)][^"]*(?="))|(?<=")(?=")|(?<=,)(?:[^,])*(?=$)
  • Also see this post
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s