admin管理员组

文章数量:1418411

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.

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.

Share Improve this question asked Jul 4, 2013 at 11:05 Royi NamirRoyi Namir 149k144 gold badges493 silver badges831 bronze badges 2
  • My RegExp approach would be to simply .replace(/-/g, "") – Alex K. Commented Jul 4, 2013 at 11:10
  • @AlexK. yup. but sometimes you want to have more knowledge on a certain topic...(rgx) – Royi Namir Commented Jul 4, 2013 at 11:11
Add a ment  | 

2 Answers 2

Reset to default 9

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./r/CrgTOrXC8E

^[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'))

本文标签: javascriptRegex for limited numbersunlimited middle dashesStack Overflow