How to check if a string contains only numbers?
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 开发者_C百科() etc ..?
What i am trying to check for is mobile numbers, so 077 234 211 should be accepted, but other alphas should not be
You could use a regular expression like this
If Regex.IsMatch(number, "^[0-9 ]+$") Then
...
End If
Use IsNumeric Function :
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})$
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
You may just remove all spaces and leverage 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 digits use:
If number.All(AddressOf Char.IsDigit) Then
精彩评论