Take the 2-minute tour ×

i need a regular expression validation for

numeric digits grouped as X-XXXXX-XXX-X

can any one help?

share|improve this question
For every X you replace it with [0-9] and you're done?! –  Stephen Quan Jan 27 '12 at 17:12
add comment

5 Answers

up vote 2 down vote accepted
Regex reg =  new Regex("\b[0-9]\-[0-9]{5}\-[0-9]{3}\-[0-9]\b");
share|improve this answer
Thanx for the solution... –  chamara Jan 27 '12 at 17:26
add comment

Here is what I use for checking social security numbers that user's input:

Public Shared Function CheckSSNFormat(ByVal text As String) As Boolean
    Dim digits As String = Regex.Replace(text, "[^0-9]", "")
    Return digits.Length = 9
End Function

It doesn't check that they are input in a specific format, but that might be better depending on what you really need -- so just thought I'd give you another option, just incase.

The above just removes everything except digits, and returns true if there are 9 digits (a valid SS#). It does mean some goofy user could enter something like: hello123456789 and it would accept it as valid, but that is fine for me, and I'd rather do that than not accept 123456789 just because I was looking for 123-45-6789 only.

Later I use this to save to my database:

Public Shared Function FormatSSNForSaving(ByVal text As String) As String
    If text = "" Then text = "000-00-0000"
    Return Regex.Replace(text, "[^0-9]", "")
End Function

and this anytime I want to display the value (actually I use this one for phone numbers, turns out I never display the SS# so don't have a function for it):

Public Shared Function FormatPhoneForDisplay(ByVal text As String) As String
    If text.Length <> 10 Then Return text
    Return "(" & text.Substring(0, 3) & ") " & text.Substring(3, 3) & "-" & text.Substring(6, 4)
End Function
share|improve this answer
add comment

(^\d{1}-\d{5}-\d{3}-\d{1}$), this should do.

share|improve this answer
add comment

you could also use round brackets to extract the numbers if you want:


and get the values with $1 $2 etc. in the Regex.Replace() function

share|improve this answer
add comment
Regex pattern = new Regex("\b\d-\d{5}-\d{3}-\d\b");

\b - word boundary
\d - digit
share|improve this answer
add comment

Your Answer


