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

问题描述

|
Dim number As String = \"07747(a)\"

If number.... Then

endif
我希望能够检查字符串中是否只有数字,如果它仅包含数字,然后运行if语句中的内容?我要用什么检查来检查字符串是否仅包含数字并且不包含alpha ot()等。 我要检查的是手机号码,因此应该接受077 234 211,但不应接受其他字母     

解决方法

您可以使用这样的正则表达式
If Regex.IsMatch(number,\"^[0-9 ]+$\") Then

...

End If
    ,使用IsNumeric函数:
IsNumeric(number)
如果要验证电话号码,则应使用正则表达式,例如:
^\\(?([0-9]{3})\\)?[-. ]?([0-9]{3})[-. ]?([0-9]{3})$
    ,http://msdn.microsoft.com/zh-CN/library/f02979c7(v=VS.90).aspx 如果不需要返回的整数,则无法传递任何内容
if integer.TryParse(number,nothing) then
    ,您可以删除所有空格并利用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