Lucas
Lucas

Reputation: 47

regex 13 digits phone number with dash

I have an application that needs to handle validation for phone numbers. Phone numbers are required to have 13 characters (sum of numbers and dashes). There must be at least 1 dash and a maximum of 3 dashes. The starting character must be a digit. How can I create a regex for this validation? Here is my regex string. /^(?:[0-9]-*){13}$/ It doesn't work exactly what I expected

Upvotes: 1

Views: 1522

Answers (3)

I assumed the number of digits are not known. I am looking for number of dashes between 1 and 3 between the numbers

texts = ['1-2-3-4-5','123-4567-8901','123-45-67-890','123-456728901','1234567890123','123--67890123','-234567890123','123456789012-','-23456789012-']

for text in texts:
    print(text,re.findall(r"^\d+-?\d+-?\d+-?\d+$",text))

output:

1-2-3-4       ['1-2-3-4']
123-4567-8901 ['123-4567-8901']
123-45-67-890 ['123-45-67-890']
123-456728901 ['123-456728901']
1234567890123 ['1234567890123']
123--67890123 []
-234567890123 []
123456789012- []
-23456789012- []

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627126

You can use

^(?=.{13}$)[0-9]+(?:-[0-9]+){1,3}$
^(?=.{13}$)\d+(?:-\d+){1,3}$

See the regex demo. Details:

  • ^ - start of string
  • (?=.{13}$) - the string must contain exactly 13 chars
  • [0-9]+ / \d+ - one or more digits
  • (?:-[0-9]+){1,3} / (?:-\d+){1,3} - one, two or three repetitions of a hyphen followed with one or more digits
  • $ - end of string.

See the regex graph:

enter image description here

A JavaScript demo:

const texts = ['123-4567-8901','123-45-67-890','123-456728901','1234567890123','123--67890123','-234567890123','123456789012-','-23456789012-'];
const regex = /^(?=.{13}$)\d+(?:-\d+){1,3}$/;
for (const text of texts) {
    console.log(text, "=>", regex.test(text));
}

Upvotes: 2

JvdV
JvdV

Reputation: 75930

So 13 characters in total with a maximum of 3 dashes and a minimum of 1 means 10 digits right? Therefor your characters are ranging 11-13?

If so, try:

^(?=(?:\d-?){10}$)\d+(?:-\d+){1,3}

See an online demo

  • ^ - Start line anchor.
  • (?= - Open a positive lookahead:
    • (?: - Open a non-capture group:
      • \d-? - Match a digit and optional hyphen.
      • ){10}$) - Close the non-capture group and match it ten times before the end-string anchor. Then close the lookahead.
  • \d+ - 1+ Digits.
  • (?: - Open a 2nd non-capture group:
    • -\d+ - Match an hyphen and 1+ digits.
    • ){1,3} - Close non-capture group and match it 1-3 times.

Upvotes: 3

Related Questions