Skip to content

Instantly share code, notes, and snippets.

@james-see
Created January 19, 2022 06:47
Show Gist options
  • Save james-see/e6157b40e0636c1c6ab7b5514291736c to your computer and use it in GitHub Desktop.
Save james-see/e6157b40e0636c1c6ab7b5514291736c to your computer and use it in GitHub Desktop.
greedy phone number parser with regex in python
def greedyphoneparse(basetext="I can haz phone number? +14126723436") -> list():
"""Very flexible phone number parser that does not require country code.
Args:
basetext (string, optional): The text to parse.
Defaults to "I can haz phone number? +14126723436".
Returns:
list: List of phonenumbers found or empty list.
"""
pattern = '[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}'
phonenumbersfound = re.findall(pattern, basetext)
if len(phonenumbersfound) > 0:
return phonenumbersfound
else:
return []
@james-see
Copy link
Author

Yes, the phonenumbers package exists that is based on Google's phone number parser. The problem (BIG problem) IMO is that it requires knowledge of the country code a priori, which is no bueno.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment