Extract phone numbers from text

This script extracts phone numbers from a given text string. It uses a regular expression to identify phone numbers that may include area codes (with or without parentheses), separators (spaces, hyphens, or dots), and optional extensions. The function returns a list of all matched phone numbers found in the input text.

Script windmill

by henri186 ยท 4/17/2024

  • Submitted by henri186 Python3
    Created 755 days ago
    1
    import re
    2
    from typing import List
    3
    
    
    4
    
    
    5
    def main(
    6
        text: str = "Example of text with several numbers formats \n Los Pollos Hermanos \n 8500 Pan American Fwy NE, \n Albuquerque, NM 87113, USA \n 505-503-4455 \n 234-455-9493 ") -> List[str]:
    7
        phoneRegex = re.compile(
    8
            r"""(
    9
            (\d{3}|\(\d{3}\))?                 # area code
    10
            (\s|-|\.)?                             # separator
    11
            (\d{3})                               # first 3 digits
    12
            (\s|-|\.)                               # separator
    13
            (\d{4})                               # last 4 digits
    14
            (\s*(ext|x|ext.)\s*(\d{2,5}))?    # extension
    15
            )""",
    16
            re.VERBOSE,
    17
        )
    18
    
    
    19
        matches = []
    20
        for numbers in phoneRegex.findall(text):
    21
            matches.append(numbers[0])
    22
    
    
    23
        return matches
    24