【发布时间】:2011-05-26 13:01:36
【问题描述】:
Dim number As String = "07747(a)"
If number.... Then
endif
我希望能够检查字符串内部是否只有数字,如果它只包含数字然后运行 if 语句中的任何内容?我用什么检查来检查字符串是否只包含数字而没有字母 ot () 等..?
我要检查的是手机号码,所以应该接受 077 234 211,但不应该接受其他字母
【问题讨论】:
标签: vb.net
Dim number As String = "07747(a)"
If number.... Then
endif
我希望能够检查字符串内部是否只有数字,如果它只包含数字然后运行 if 语句中的任何内容?我用什么检查来检查字符串是否只包含数字而没有字母 ot () 等..?
我要检查的是手机号码,所以应该接受 077 234 211,但不应该接受其他字母
【问题讨论】:
标签: vb.net
你可以使用这样的正则表达式
If Regex.IsMatch(number, "^[0-9 ]+$") Then
...
End If
【讨论】:
Regex.IsMatch(input,pattern) 方法?后者似乎更清晰。
IsNumeric(number)
如果要验证电话号码,应使用正则表达式,例如:
^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{3})$
【讨论】:
IsNumeric 对于十进制数也返回 true,这可能不是 OP 想要的。
http://msdn.microsoft.com/en-us/library/f02979c7(v=VS.90).aspx
如果你不需要像这样返回的整数,你可以不传递任何东西
if integer.TryParse(number,nothing) then
【讨论】:
Trim 不会删除数字之间的空格。
您可以删除所有空格并利用 LINQ All:
判断一个序列的所有元素是否满足一个条件。
如下图使用:
Dim number As String = "077 234 211"
If number.Replace(" ", "").All(AddressOf Char.IsDigit) Then
Console.WriteLine("The string is all numeric (spaces ignored)!")
Else
Console.WriteLine("The string contains a char that is not numeric and space!")
End If
要仅检查字符串是否仅包含数字,请使用:
If number.All(AddressOf Char.IsDigit) Then
【讨论】: