Parsing with Regular Expressions - All-Alpha-Character String | | Is there a function in .NET that will determine if all characters in a string are Alpha? There is no intrinsic function in .NET or VB6 to do this, but the following functions show the VB6 and .NET methods of accomplishing this. Moving from Clipper over 10 years ago, I wrote a VB3 function to replace the Clipper IsAllAlpha function. The code for that method is shown below.
Function IsALLAlpha(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)
AsciiVal = Asc(nc)
If Not ((AsciiVal > 64 And AsciiVal < 91) Or _
(AsciiVal > 96 And AsciiVal < 123)) _<BR>
Then
Return False
End If
Next i
Return True
End Function
|
In .NET, the function shown above, can be replaced with the Regular Expression functionality shown below. The code is not only much simpler, but faster.
Public Function IsALLAlpha(ByVal Source As String) As Boolean
'Returns True if the string contains only a-z and A-Z or string is empty
'Returns False otherwise
' the expression says,
' beginning with the first char of the string (^),
' ensure that zero or more (*) chars are all alpha
Return Regex.IsMatch(Source, "^[a-zA-Z]*$")
End Function
| |