-3

I have custom string containing text and phone number. How I can extract this number?

Example text: Lorem ipsum +44 12-45-243 dolor 00(49) 812 234 234

EDIT: Phone number can be of any given format.

pixel
  • 24,905
  • 36
  • 149
  • 251

3 Answers3

2

Here is a thread about regex expresions on phone numbers:

A comprehensive regex for phone number validation

I believe it will be helpful for your task.

Here is one of the most upvoted regex for 7 to 10 digits:

^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$

Edit: Sorry, I meant to make it as a comment but I don't have the reputation yet.

Community
  • 1
  • 1
Marcelo
  • 401
  • 2
  • 4
  • 1
    You should excerpt the relevant parts from the linked answer as link only answers are frowned upon. – Trevor Freeman Jul 23 '14 at 20:02
  • Thanks for the heads up. I had no idea. The extract would be huge, but I will see if I can get the most important pieces. – Marcelo Jul 23 '14 at 20:03
  • How do I make this so it can extract the number from a string, anywhere that the phone number may be? – Kousha Feb 17 '17 at 00:29
2

Ok I found a solution.

I can use libphonenumber and findNumbers function.

pixel
  • 24,905
  • 36
  • 149
  • 251
1

first of all you could remove all the spaces, dashes and ... then just read the string and keep attached numbers in an array, then check if the number is valid with whatever your validation algorithm is. This will work but sure it is not efficient.

Lrrr
  • 4,755
  • 5
  • 41
  • 63
  • 1
    This is probably the way since OP was unable to define what he needs. Reminds me of the famous quote `If one does not know to which port one is sailing, no wind is favourable` - Lucius Annaeus Seneca – user3437460 Jul 23 '14 at 20:14
  • @user3437460 I would like to find phone numbers for all countries/regions of the world that may appear in text stream. – pixel Jul 23 '14 at 20:22
  • @pixel you can find country codes http://countrycode.org/. And you could check the numbers you retrieve that they meet any of this codes or not, and also you could check number length but I dont think there is a country code check algorithm because in every country it's code changes in time, so it is all you have, although you code have a verification like calling. – Lrrr Jul 24 '14 at 06:28