Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of RegEx in vb6

Tags:

regex

vb6

I need to validate a string, which might contain alphanumeric as well as special character, where as I have to pass the one which has only Alpha chars (no numbers or any other special characters are allowed)

In a current method I use ASCII numbers to evaluate each character if its alpha or not. Is there any other efficient way to discover the presence of special characters or numbers in the string? Like can't we use Like or something to check once than going character by character?

For y = 2 To Len(sString)
    If Not ((Asc(Mid$((sString,y,1))>64 AND Asc(Mid$((sString,y,1))<91) OR _
    (Asc(Mid$((sString,y,1))>96 AND Asc(Mid$((sString,y,1))<123)) Then
        //Display an error msg
        Exit For
    End If
Next y
like image 307
InfantPro'Aravind' Avatar asked Nov 29 '22 16:11

InfantPro'Aravind'


2 Answers

You can use regular expressions in VB6. You have to add a reference to the "Microsoft VBScript Regular Expressions 5.5" library to your project. You can then use the following:

Dim rex As RegExp
Set rex = New RegExp
rex.Pattern = "[^a-zA-Z]"
If rex.Test(s) Then
    ' Display error message
End If

When I originally answered this question, it was tagged as VB.NET; for future reference, my original .Net-based answer is retained below

As you thought, this can be done with regular expressions (don't forget Imports System.Text.RegularExpressions:

If Regex.IsMatch(s, "[^a-zA-Z]") Then
    ' Display error msg
End If

Also, the original code reads like VB6 code, not VB.NET. Here is a much more readable way to write the original non-regex code:

For Each ch As Char In someString
    If Not (ch >= "a"c AndAlso ch <= "z"c OrElse ch >= "A"c AndAlso ch <= "Z"c) Then
        ' Display error msg
        Exit For
    End If
Next
like image 76
Sven Avatar answered Dec 06 '22 09:12

Sven


VBA has a native Like operator: its syntax is non-standard e.g. its multi-character wildcard is * and the NOT operator is !:

If sString Like "*[!A-Za-z]*" Then
  ' Display an error msg
End If
like image 25
onedaywhen Avatar answered Dec 06 '22 09:12

onedaywhen