Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract phone numbers from string using regex?

I need to extract some phone numbers from large strings in rails. These numbers will come in a variety of formats and could have multiple phone numbers in a single string.

Here is an example of the types of formats that occur:

  • 022 1234567
  • 021 123 2345
  • 0271233211
  • 021-233-9123
  • 09 123 32112
  • 021 2331231 or 021 321123123

What is the most efficient way to extract phone numbers like this that appear within a body of text?

UPDATE: Thanks for the answers. After testing some of them I realise that I should include more examples. Here are some more that don't appear in the list above:

  • 622 32281
  • 5754321
  • 092213212
  • (09)1234321
like image 392
startupsmith Avatar asked Mar 10 '26 17:03

startupsmith


1 Answers

I would keep it simple:

\d{2}[\s\d-]+

Two numbers, one or more of whitespace, numbers or a hyphen.

Require more characters with:

\d{2}[\s\d-]{5,}

(two numbers and 5 or more of whitespace, numbers of hyphens) which will reduce the number of mis-hits.

These will include an extra space following the phone-number, but the results could be trimmed.

Rather than trim, though, I would remove the hyphens and whitespace and count the number of digits leftover to recognise them as phone numbers.

If the phone numbers always start with a 0:

0\d[\s\d-]{5,}\d

this ends with a number, so drops the space at the end in the earlier examples.

Added following the further examples:

\b[\s()\d-]{6,}\d\b
like image 178
Andy G Avatar answered Mar 12 '26 06:03

Andy G



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!