-1

I need a regular expression for a phone number.

Example,

1234567899 should be (123)(456)(7899)
12345678 should be (123)(456)(78)
1234567 should be (123)(456)(7)
123456 should be (123)(456)
12345 should be (123)(45)
123 should be (123)
1 should be (1)

I tried /([0-9]{0,3})([0-9]{0,3})([0-9]{0,4})/ and /([0-9]{3})([0-9]{3})([0-9]{4})/

But it takes only when all the 10 numbers are in the input.

I need match then replace with (

brandonscript
  • 68,675
  • 32
  • 163
  • 220
Sahal
  • 4,046
  • 15
  • 42
  • 68

3 Answers3

1

This would appear to work:

/(\d{1,3})(\d{1,3})?(\d{1,4})?/

Live test here

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
1

Check this : /^\(\d{0,3}\)(\(\d{0,3}\))?(\(\d{0,4}\))?$/

https://regex101.com/r/qC0fS9/2

KAD
  • 10,972
  • 4
  • 31
  • 73
  • This would appear to match the brackets? OP has the raw digits, and wants to add brackets. Also, no need for `[]` around `\d`. – Blorgbeard Aug 21 '15 at 04:37
  • Yeah I updated the regex and removed `[]`, From my understanding I though he wanted to look for the brackets.. Anyway the question has an answer now.. – KAD Aug 21 '15 at 04:50
1

use this pattern

((^\d{1,3})|(?<=^\d{3})(\d{1,3})|(\d+$))  

or simplified to

(^\d{3}|(?<=^\d{3})\d{3}|\d+$)

and replace with (\1)

Demo

alpha bravo
  • 7,838
  • 1
  • 19
  • 23