Regular expression for limited numbers, unlimited middle dash?

User can fill in the phone number. (only numbers and dashes, dashes are optional)

It can have as many (medium) dashes ( - ), but the total number of digits should be 10.

I controlled by writing a regular expression using a positive "-" in numbers:

^(?=.*\-)[0-9\-]+$

But I have 2 problems:

  • a trait (in my regular expression) may also be at the beginning and at the end and is not valid .

  • I was not able to apply 10-digit restrictions.

ps examples of valid examples:

050-6783828 050-678-38-28 0506783828

not :

-0506783826 0506783826- 050678--3826

ps2 please note that this question is marked as regex. I am not looking for js (non-regex) solutions.

+6
source share
2 answers

I think you need something like this:

 ^\d(?:-?\d){9}$ 
  • Start with a number.
  • 9 times: an optional dash and another digit.

Working example: http://rubular.com/r/CrgTOrXC8E

+8
source
 ^[0-9](-?[0-9]){8}-?[0-9]$ 

The number at the beginning and the end, 8 groups of optional dashes and numbers, plus an optional dash before the last digit

Only one dash is allowed between adjacent digits.

 var pat = new RegExp('^[0-9](-?[0-9]){8}-?[0-9]$') // correct console.log(pat.test('0506783828')) console.log(pat.test('0-5-0-6-7-8-3-8-2-8')) // incorrect console.log(pat.test('0506783828-')) console.log(pat.test('-0506783828')) console.log(pat.test('05--06783828')) 
+2
source

Source: https://habr.com/ru/post/948702/


All Articles