Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for limited numbers, unlimited middle dashes?

A user can fill a phone number. ( only digits and dashes , dashes are not mandatory)

He can have as much (middle) dashes (-) but the total count of digits must be 10.

I've managed writing a regex using positive lookahead of "-" in numbers :

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

But I have 2 problems with that :

  • the dash ( in my regex) can be also in the beginning and at the end and that's not valid.

  • I haven't succeed applying the 10 digits restrictions.

p.s. examples of valid examples :

050-6783828 050-678-38-28 0506783828

not valid :

-0506783826 0506783826- 050678--3826

p.s.2 please notice this question is tagged as regex. I'm not looking for js (non-regex) solutions.

like image 303
Royi Namir Avatar asked Jul 04 '13 11:07

Royi Namir


2 Answers

I think you want something like this:

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

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

like image 179
Kobi Avatar answered Nov 19 '22 02:11

Kobi


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

A digit at the begin and end, 8 groups of optional dash and digit, plus optional dash before last digit

Only one dash is allowed between eatch neighbouring 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'))
like image 41
Danubian Sailor Avatar answered Nov 19 '22 01:11

Danubian Sailor