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:
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With