Check only digits in VB.NET String

I want to run a string check right before adding it to a StringBuilder, to make sure that only numeric characters are in the string. What is an easy way to do this?

+5
source share
9 answers

Use Integer.TryParse (), it will return true if there are only digits in the string. The maximum value of Int32 is 2,147,483,647, so if your value is less, then your penalty. http://msdn.microsoft.com/en-us/library/f02979c7.aspx

You can also use Double.TryParse (), which has a maximum value of 1.7976931348623157E + 308, but it will have a decimal point.

, , .

string test = "1112003212g1232";
        int result;
        bool append=true;
        for (int i = 0; i < test.Length-1; i++)
        {
            if(!Int32.TryParse(test.Substring(i,i+1),out result))
            {
                //Not an integer
                append = false;
            }
        }

append true, . , , .

+8

VB.Net, , .

If IsNumeric("your_text") Then
  MessageBox.Show("yes")
Else
  MessageBox.Show("no")
End If
+8

:

Dim reg as New RegEx("^\d$")

If reg.IsMatch(myStringToTest) Then
  ' Numeric
Else
  ' Not
End If

:

linq , VB.Net 2008/2010.

Dim isNumeric as Boolean = False

Dim stringQuery = From c In myStringToTest 
                          Where Char.IsDigit(c) 
                          Select c

If stringQuery.Count <> myStringToTest.Length Then isNumeric = False
+4

RegEx, char.IsNumber.

All ( #, , VB.net):

string value = "78645655";
bool isValid = value.All(char.IsNumber);

char, IsDigit.

+3

2 :

LINQ:

Dim foo As String = "10004"
Array.Exists(foo.ToCharArray, Function(c As Char) Not Char.IsNumber(c))

LINQ ( VB.Net # ):

foo.All(Function(c As Char) Char.IsNumber(c))
+3

, Integer.TryParse .

UInteger.TryParse, . , "+":

Dim test As String = "1444"
Dim outTest As UInteger
If Not test.StartsWith("+") AndAlso UInteger.TryParse(test, outTest) Then
    MessageBox.Show("It just digits!")
End If

ULong.TryParse .

+2

! . this, this (about.com) this ( VB.NET dev).

+1

Integer.TryParse,

+1

Assuming you are looking at relatively short strings that will never have a number greater than the Max Int32 value, use the Gage solution. If it's variable length and sometimes you can overflow, use Regex ( System.Text.RegularExpressions)

The regular expression for checking only the number of numbers is pretty common: ^[0-9]+$

Check here for a very good Regex explanation.

+1
source

All Articles