Parsing with Regular Expressions - IsDigit | | How can I easily tell if the first character of a string is numeric? There is no intrinsic function in .NET or VB6 for doing this. Being an old Clipper programmer, when I moved to VB3, I wrote a VB function to replace the Clipper function IsDigit, which returns True if the first character of a string is numeric. The code for that function is shown below.
Function IsDigit(ByVal cS As String) As Boolean
' Returns True if first character of cString is digit,
' otherwise False.
Dim cTemp As String
Dim vTemp As Integer
cTemp = cS.Substring(0, 1) ' get first character first
' cant pass Asc() an empty string
If cTemp.Trim.Length = 0 Then
Return False
End If
vTemp = Asc(cTemp)
Return (vTemp > 47 AndAlso vTemp < 58)<BR>
End Function
|
In .NET, using a Regular Expression is much simpler, as shown by the code below. Although you would have to run performance tests to determine if invoking the Regex Engine is slower or faster in this case, a knowledge of Regular Expressions will be a plus for any developer in the long run.
Public Function IsDigit(ByVal Source As String) As Boolean
' Returns True if first character of Source is digit,
' otherwise False.
' the expression says to match the first character in the
' string for numeric
Return Regex.IsMatch(Source, "^\d.*$", RegexOptions.Singleline)
End Function
| |