简体   繁体   中英

Extract phone number from text in python

I want to extract phone number from text. I able to extract phone number from text when all digits are presents on single line. But When some digits are present in next line then regex is not working.

Here is my text:

I will be out of the office. Please send me an email and text my mobile +45
20 32 40 08 if any urgency.

In above text +45 is on first line and 20 32 40 08 presents on second line. I unable to extract phone numbers from text when text like above text. When digits are present on same single line then it's working fine.

Here is my regex:

reg_phonestyle = re.compile(r'(\d{2}[-\/\.\ \s]??\d{2}[-\/\.\ \s]??\d{2}[-\/\.\ \s]??\d{2}[-\/\.\ \s]??\d{2}|\(\d{3}\)\s*\d{3}[-\/\.\ \s]??\d{4}|\d{3}[-\/\.\ \s]??\d{4})')

You can specify an additional flag to perform a MULTILINE search. Given your example I propose the following solution:

import re

input_str = '''                                                                 

I will be out of the office. Please send me an email and text my mobile +45     
20 32 40 08 if any urgency.                                                     

'''
phone_reg = re.compile("([0-9]{2,4}[-.\s]{,1}){5}", re.MULTILINE)

print(phone_reg.search(input_str).group(0))

Where this regexp find 5 groups of: 2 to 4 digits followed by 0 or 1 spacing character

Hope this helps

This is my way to get phone number. actually i want more examples to verify my regex.

import re
strs = '''                                                                 
I will be out of the office. Please send me an email and text my mobile +45     
20 32 40 08 if any urgency.                                                     
'''
phone = re.compile("(?<=mobile\s)(.?[0-9]|\s)+", re.S)

print( " ".join(phone.search(strs).group(0).split()) ) # remove \n and space and etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM