Skip to content

Instantly share code, notes, and snippets.

@jhecking
Created November 14, 2012 05:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhecking/4070551 to your computer and use it in GitHub Desktop.
Save jhecking/4070551 to your computer and use it in GitHub Desktop.
Phone number regular expression
# A phone number consists of up to six groups of digits which may or may not
# be separated from each other using one of the separater characters dot ".",
# dash "-" or space " ". The six groups are:
# (1) International country code, which is a one to four digit number
# prefixed by a plus sign "+". The plus sign is optional if - and only if -
# the country code is immediately followed by a separator char.
# The whole country code group is optional.
# (2) Area code, which is a one to three digit number enclosed in parenthesis
# "()". The parenthesis are optional if - and only if - the area code is
# immediately followed by a separator char.
# The whole area code group is optional.
# (3-6) Two to four groups of three to five digits each, optionally seprated
# by a single separator char.
#
PHONE_REGEX = %r{
(?<! [\w\$-] ) # negative look-behind: number is not immediately
# preceeded by a word character, "$" or "-"
(?: \+ \d{1,4} | \+? \d{1,4} [\ \.\-] )? # (1) international country code
(?: \( \d{1,3} \) | \( \d{1,3} \) [\ \.\-] | \d{1,3} [\ \.\-] )? # (2) area code
(?: \d{3,5} [\ \.\-]? ){1,3} \d{3,5} # (3-6) local number
\b # word boundary
}x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment