如何检查字符串是否只包含数字?

时间:2011-05-26 13:01:36

标签: vb.net

Dim number As String = "07747(a)"

If number.... Then

endif

我希望能够检查字符串内部是否只有数字,如果它只包含数字,那么运行if语句中的任何内容?我用什么检查来检查字符串是否只包含数字而不包含alpha ot()等。?

我想要检查的是手机号码,所以应该接受077 234 211,但其他alphas不应该

4 个答案:

答案 0 :(得分:59)

您可以使用像这样的正则表达式

If Regex.IsMatch(number, "^[0-9 ]+$") Then

...

End If

答案 1 :(得分:28)

使用IsNumeric Function

IsNumeric(number)

如果要验证电话号码,则应使用正则表达式,例如:

^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{3})$

答案 2 :(得分:8)

http://msdn.microsoft.com/en-us/library/f02979c7(v=VS.90).aspx

如果您不需要返回的整数,则可以不传递任何内容

if integer.TryParse(number,nothing) then

答案 3 :(得分:6)

您可以删除所有空格并利用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