Extract phone number from text using re?

Viewed 3225

I need to extract phone number, but my regex don't extract all numbers

text = '+79082343434   8(912)2342554,  +7 982 342 sdfdsf 34 34 fsf 8-923-132-34-23 +7 982 342 34 34! sdfsd'
r = re.compile(r"\+?\d{1,3}?[- .]?\(?(?:\d{2,3})\)?[- .]?\d\d\d[- .]?\d\d\d\d")
phone = r.findall(text)

Out[7]: ['+79082343434', '8(912)2342554']

Desire output:

['+79082343434', '8(912)2342554', '8-923-132-34-23', '+7 982 342 34 34']

How can I improve this expression to get all phone numbers?

2 Answers

This should find all the phone numbers in a given string

re.findall(r'+?(?[1-9][0-9 .-()]{8,}[0-9]', text)

 >>> re.findall(r'[\+\(]?[1-9][0-9 .\-\(\)]{8,}[0-9]', text)
 ['+79082343434   8(912)2342554', '8-923-132-34-23', '+7 982 342 34 34']

Basically, the regex lays out these rules

  1. The matched string may start with + or ( symbol
  2. It has to be followed by a number between 1-9
  3. It has to end with a number between 0-9
  4. It may contain 0-9 (space) .-() in the middle.
Related