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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6138896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 15:30:57  来源:igfitidea点击:

How to check if a string contains only numbers?

vb.net

提问by Beginner

Dim number As String = "07747(a)"

If number.... Then

endif

I want to be able to check inside the string to see if it only has number, if it does only contain numbers then run whatever is inside the if statment? What check do i use to check if the string only contains numeric and no alpha ot () etc ..?

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

What i am trying to check for is mobile numbers, so 077 234 211 should be accepted, but other alphas should not be

我要检查的是手机号码,因此应该接受 077 234 211,但不应接受其他字母

回答by Bala R

You could use a regular expression like this

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

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

...

End If

回答by CD..

Use IsNumeric Function:

使用IsNumeric 函数

IsNumeric(number)

If you want to validate a phone number you should use a regular expression, for example:

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

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

回答by Matt

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

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

You can pass nothing if you don't need the returned integer like so

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

if integer.TryParse(number,nothing) then

回答by Wiktor Stribi?ew

You may just remove all spaces and leverage LINQ All:

您可以删除所有空格并利用 LINQ All

Determines whether all elements of a sequence satisfy a condition.

确定序列的所有元素是否都满足条件。

Use it as shown below:

如下图使用:

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

To only check if a string consists of only digitsuse:

仅检查字符串是否仅包含数字,请使用:

If number.All(AddressOf Char.IsDigit) Then