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
2 Answers
Reset to default 9I 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'))
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745275304a4620002.html
评论列表(0条)