Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to fetch phone number from string

I want regex which finds out continues max 12 digits long number by ignoring space, plus (+), parenthesis & dash, e.g:

Primary contact number +91 98333332343 call me on this
My number is +91-983 333 32343
2nd number +1 (983) 333 32343, call me
Another one 983-333-32343
One more +91(983)-333-32343 that's all
121 street pin code 421 728 & number is 9833636363

Currently, I have a regex, which does the job of fetching contact numbers from string:

/* This only work for the first case not for any other
   and for last one it outputs "121" */

\\+?\\(?\\d*\\)? ?\\(?\\d+\\)?\\d*([\\s./-]?\\d{2,})+

So what can be done here to support all the above cases, in short ignoring special characters and length should range from 10-12.

like image 442
Dheeraj Agrawal Avatar asked Sep 20 '16 06:09

Dheeraj Agrawal


People also ask

Can regex be used for numbers?

The regex [0-9] matches single-digit numbers 0 to 9. [1-9][0-9] matches double-digit numbers 10 to 99. That's the easy part. Matching the three-digit numbers is a little more complicated, since we need to exclude numbers 256 through 999.


1 Answers

I see that there are numbers ranging from 10 to 13 digits.

You may use

/(?:[-+() ]*\d){10,13}/g

See the regex demo.

Details:

  • (?:[-+() ]*\d){10,13} - match 10 to 13 sequences of:
    • [-+() ]* - zero or more characters that are either -, +, (, ), or a space
    • \d - a digit

var re = /(?:[-+() ]*\d){10,13}/gm; 
var str = 'Primary contact number +91 98333332343 call me on this\nMy number is +91-983 333 32343\n2nd number +1 (983) 333 32343, call me\nAnother one 983-333-32343\nOne more +91(983)-333-32343 that\'s all\n121 street pin code 421 728 & number is 9833636363';
var res = str.match(re).map(function(s){return s.trim();});
console.log(res);
 
like image 104
Wiktor Stribiżew Avatar answered Oct 11 '22 06:10

Wiktor Stribiżew