2012-01-27 104 views
0

我需要位数正则表达式验证

numeric digits grouped as X-XXXXX-XXX-X 

任何一个可以帮助正则表达式验证?

+1

对于每个X你用[0-9]替换它,你完成了?! – 2012-01-27 17:12:14

回答

2
Regex reg = new Regex("\b[0-9]\-[0-9]{5}\-[0-9]{3}\-[0-9]\b"); 
+0

Thanx解决方案... – chamara 2012-01-27 17:26:06

0
[0-9]-[0-9]{5}-[0-9]{3}-[0-9] 

你也可以使用圆括号中提取的数字,如果你想:

([0-9])-([0-9]{5})-([0-9]{3})-([0-9]) 

,并获得在Regex.Replace()函数$ 1 $ 2等的值

0
Regex pattern = new Regex("\b\d-\d{5}-\d{3}-\d\b"); 

\b - word boundary 
\d - digit 
1

(^\d{1}-\d{5}-\d{3}-\d{1}$),应该这样做。

1

以下是我用于检查社会安全号码用户的输入:

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 

它不检查,他们是在一个特定的格式输入,但可能是更好的根据是什么你真的需要 - 所以只是想我会给你另一种选择,只是开始。

以上只是删除数字以外的所有内容,如果有9位数字(有效的SS#),则返回true。这确实意味着一些愚蠢的用户可能会输入这样的内容:hello123456789,它会接受它是有效的,但这对我来说很好,我宁愿这样做,也不愿意接受123456789,因为我只是在寻找123-45-6789 。

后来,我用它来保存到我的数据库:

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 

,这只要我想显示的值(其实我用这一个电话号码,原来我从来没有显示SS#所以不要没有它的功能):

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