0

how can i write a regex to find a phone number

this is a number 09876 09875

it should detect 09876 09875 as a whole number

this is a number +17865 8658 u98765

this should detect two numbers +17865 8658 and 98765

skcrpk
  • 558
  • 5
  • 18
  • i am trying to detect phone number with spaces ,+ (,- signs in it – skcrpk Mar 19 '13 at 13:31
  • Possible duplicate: http://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation – Ben McCormick Mar 19 '13 at 13:33
  • I'm still new to regex (hence not posting this as an answer), but could this do it? `[0-9\+\s]+` – John Bustos Mar 19 '13 at 13:34
  • Do you have correct inputs and just want to extract the number groups or do you want to test if a given input contains a valid phone number according to your specs? – Simon Mar 19 '13 at 14:01
  • yes trying to test the given input and test if it is valid phone number with above rules – skcrpk Mar 19 '13 at 14:16

2 Answers2

1

Remove spaces and match plus sign with following numbers:

var input   = 'this is a number +17865 8658 u98765',
    outputs = input.replace(/ /g, '').match(/\+?\d+/g);

Output:

["+178658658", "98765"]

Without replacing spaces:

var input   = 'this is a number +17865 8658 u98765',
    outputs = input.match(/\+?\d( *\d+)+/g);

Output:

["+17865 8658", "98765"]
hsz
  • 148,279
  • 62
  • 259
  • 315
  • i do not want to remove spaces keep them as they are like if the number is +16786 876 986 it should detect it but if the number is +1234 u89 97 it should detect two number +1234 and 89 97 – skcrpk Mar 19 '13 at 13:34
  • it should detect this number a whole number +123 456 788 not as three separate numbers – skcrpk Mar 19 '13 at 14:21
1

Use following Regex

/[+0-9]+(?:\.[0-9]*)?/g

for working example click

Mansoor Jafar
  • 1,458
  • 3
  • 15
  • 31