Extract phone numbers from string using regex?
regex, ruby, ruby-on-rails, ruby-on-rails-3
Solution
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
Problem
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