Regex for Validating Telephone Numbers

Prompt

regex for telephone numbers
Python

Result

import re

def validate_telephone_number(number):
    """
    Validate a telephone number using regular expression.

    Args:
        number (str): The telephone number to be validated.

    Returns:
        bool: True if the telephone number is valid, False otherwise.
    """
    pattern = r'^\+?[1-9]\d{1,14}$'
    # ^\+? matches an optional '+' at the beginning of the number
    # [1-9] matches a digit from 1 to 9
    # \d{1,14} matches 1 to 14 digits
    # $ matches the end of the string

    return bool(re.match(pattern, number))
Python

To use the validate_telephone_number function, simply pass a telephone number as a string to the function. It will return True if the telephone number is valid, and False otherwise.

Example usage:

number = '+1234567890'
valid = validate_telephone_number(number)
print(valid)  # Output: True

number = '123-456-7890'
valid = validate_telephone_number(number)
print(valid)  # Output: False
Python