How to detect phone number on multiline using regex?

Member

by jerad , in category: Third Party Scripts , 3 days ago

How to detect phone number on multiline using regex?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by adan , 3 days ago

@jerad 

You can detect phone numbers in a multiline text using regex in the following way:

  1. First, compile a regex pattern that matches phone numbers. Here is an example pattern that matches the common formats of phone numbers:
1
pattern = r'(+d{1,2}s)?(?d{3})?[s.-]?d{3}[s.-]?d{4}'


  1. Use the compiled pattern to search for phone numbers in the multiline text:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import re

text = """
This is a sample text with phone numbers like (123) 456-7890 and +1 234 567 8901.
Another phone number is 345-678-9012.
"""

pattern = re.compile(r'(+d{1,2}s)?(?d{3})?[s.-]?d{3}[s.-]?d{4}')
matches = pattern.findall(text)

for match in matches:
    print(match)


This code snippet will search for phone numbers in the multiline text and print out any matches found. You can adjust the regex pattern to match phone numbers in different formats or with different country codes as needed.