• Status: Solved
• Priority: Medium
• Security: Public
• Views: 1009

# Regular expression for field in the format of NNNN-NNN-NNNN

I have an Asp.net web form with an input field where people will enter the data in the format
NNNNN-NNN-NNNNN

Where N represents a number. And each set of numbers is seperated by a hyphen. Also two consecutive hyphens are not allowed. Also I need to prevent the applicaiton user from starting the number sequence with a hyphen or ending with a hyphen. So this is not allowed:
-NNNNN-NNN-NNNNN Nor -NNNNN-NNN-NNNNN-  Nor -NNNN-NNN-NNNN-

Basically the rule is a first set of numbers followed by a hyphen, followed by another set of numbers, a hyphen and followed by third set of numbers. The total number of digits entered cannot exceed 20.

Can someone help me figure this out?  I initially created this regular expression which I used to allow people to enter up to 20 numbers. The requirements have changed now so that I have to use hypens for input according to what I described earlier. This is what I initially had:
^\d{1,20}\$

This is a difficult problem I have not been able to figure out. I will offer 400 points for some expert help.
0
brgdotnet
• 3
• 2
3 Solutions

Commented:
^(?=.{1,20}\$)\d+-\d+-\d+\$
0

Commented:
"I have an Asp.net web form with an input field where  people will enter the data in the format
NNNNN-NNN-NNNNN
"

Hi! You may try this one. Hope it helps.

``````(D-)?\d{5}(-| )\d{3}(-| )\d{5}
``````
0

Commented:
^\d{1,20}-\d{1,20}-\d{1,20}\$
0

Commented:
Sorry, didn't see TOTAL digits count should be less than 20.
1) ^\d+-\d+-\d+\$
2) And set MaxLength for TextBox equal to 18
That's it
0

Commented:
Oops misprint, MaxLength should be 22 (20 digits + 2 hypens)
0

Commented:
^(?=.{1,22}\$)\d+-\d+-\d+\$ then--I didn't notice I needed to account for the hyphens.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.