Python Phone Number Pattern Matching w/ RegEx (findall)

Question:

I need to match to a NANP standard 10-digit phone number with some using – as a separator (e.g. 123-456-7890) and some will have a dot (.) as a separator (e.g. 123.456.7890).

I have tried:

numbers = "123-456-7890, 123.456.7890"
phones = re.findall("d{3}*D*d{3}*D*d{4}", numbers)
Asked By: JamesD

||

Answers:

Try this:

import re
result = re.findall('d{3}[-.]d{3}[-.]d{4}', numbers)
print(result)

Output: ['123-456-7890', '123.456.7890']

  • [-.] : match only - or .
  • d{3} : three times match any digit (0-9)
Answered By: I'mahdi
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.