KnowDotNet

Using Regular Expressions to Create Parsing Methods

Testing a String for All Numerics

by Les Smith

Is there a function to tell if all characters in a string are numeric?  There is not a built in function in NET, but the following code methods will do the job.

Before .NET, I wrote a function in VB6, called IsAllNumeric, which returned True if all of the characters in the passed string were numeric.

   Function IsALLNumeric(ByVal cS As String) As Boolean
      Dim i As Integer = 0
      
Dim nc As String ' next character
      Dim AsciiVal As Integer

      If cS.Length = 0 Then Return False

      For i = 0 To cS.Length - 1
         nc = cS.Substring(i, 1)
        
If Not (nc >= "0" And nc <= "9") Then
            Return False
         End If
      Next i
      
Return True
   End Function

However, in .NET, there is a simpler and faster way to write the same function using Regular Expressions.

   Public Function IsALLNumeric(ByVal Source As String) As Boolean
      'Returns True if the string contains only 0-9 or
      'string is empty
      'Returns False otherwise
      ' for the uninitiated in Regexes
      ' ^ is beginning of atring
      ' \ followed by a character matches the character
      ' d is any decimal character
      ' * zero or more matches
      ' $ end of the string
      ' so, to explain the expression:
      ' Beginning at the start of the string,
      ' IsMatch returns True if any number of characters are all numeric
      Return Regex.IsMatch(Source, "^\d*$")
  
End Function

If you want the IsAllNumeric function to return True only if there is at least one numeric character and all characters are numeric, you can replace the Return statement with the following line of code.  In other words, simply change the "*" to a "+".

      Return Regex.IsMatch(Source, "^\d+$")