Skip to content

Instantly share code, notes, and snippets.

@jt
Created June 5, 2011 19:49
Show Gist options
  • Save jt/1009331 to your computer and use it in GitHub Desktop.
Save jt/1009331 to your computer and use it in GitHub Desktop.
Phone number regular expression pattern
def match(number)
/\+?(\d)?[-|\.|\s]?\(?(\d{3})\)?[-|\.|\s]?(\d{3})[-|\.|\s]?(\d{4})/.match number
end
# test match and captures against possibilities
[
['3335557777', nil, '333', '555', '7777'],
['333-555-7777', nil, '333', '555', '7777'],
['333.555.7777', nil, '333', '555', '7777'],
['333 555 7777', nil, '333', '555', '7777'],
['333-555.7777', nil, '333', '555', '7777'],
['(333) 555.7777', nil, '333', '555', '7777'],
['13335557777', '1', '333', '555', '7777'],
['1-333-555-7777', '1', '333', '555', '7777'],
['1.333.555.7777', '1', '333', '555', '7777'],
['1 333 555 7777', '1', '333', '555', '7777'],
['1 333-555.7777', '1', '333', '555', '7777'],
['+1-333-555-7777', '1', '333', '555', '7777']
].each do |number|
number.each_with_index {|n,i| puts match(number[0])[i] == n}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment