find phone numbers in a string using regex in python

To find phone numbers in a string using regex in Python, you can use a regular expression and the re module.

Here's an example code block that matches ten-digit phone numbers (in the format XXX-XXX-XXXX) in a string s:

main.py
import re

s = "My phone number is 123-456-7890."

phone_regex = re.compile(r'\d{3}-\d{3}-\d{4}')
match = phone_regex.search(s)
if match:
    print(match.group())
163 chars
9 lines

In this example, phone_regex is a compiled regular expression pattern that matches the format of a phone number. The pattern r'\d{3}-\d{3}-\d{4}' specifies that it should match a string of exactly ten digits, separated by two hyphens.

We then use the search method to look for the first occurrence of this pattern in the string s. If we find a match, we print it using the group method of the match object.

You can adjust the regular expression pattern to match other formats of phone numbers as needed.

gistlibby LogSnag