Compare string to allowed characters

Ford-p

Active member
Joined
Mar 1, 2007
Messages
30
Programming Experience
Beginner
Hey,

I have a string of text and a string containing allowed characters. I want compare the string of text to the string of chars and if the text only uses the allowed characters to continue, else show a message box. Hope that makes sense.

I'm sure there is a simple way to do it with Regex, but I still don't get it 100%.

Thanks,
Joe
 
Yes, you can define the character class and negate it, if you get a match with this expression it means there exist a char not on the list.
Regex example allow only a,b,c,x,y,z (negated):
[^a-cx-y]
VB.NET:
Dim input As String = "abcxyz5"
Dim pattern As String = "[^a-cx-y]"
If Not Regex.IsMatch(input, pattern) Then
    MsgBox("valid input")
Else
    MsgBox("not valid input")
End If
Regex is defined in System.Text.RegularExpressions namespace.

You could also search repeatedly through the string and only for allows chars in character class ("^[a-cx-y]+?$") but it would be highly inefficient compared to the first suggestion that only needs to find one single char not listed before the expression is determined.

I 'always' recommend this http://www.regular-expressions.info if you're new to regex.
 
You could also use string.split, splitting the string using the allowed characters, and specifying the option to suppress empty returns. In theory, the returned array should have a length of 0 if the string is entirely composed of allowed chars
 
Thanks for the replys, I've got it working using regex. There are 24 allowed characters so splitting it would be quite messy.

Heres the code for the next person that wants to do this:
VB.NET:
        Dim strChars As String = "BCDFGHJKMPQRTVWXY2346789"

        Dim rgxPattern As New Regex("[^B-DF-HJ-KMP-RTV-Y2-46-9]", RegexOptions.Compiled)

            If Not rgxPattern.IsMatch(strText) Then
                MsgBox("valid input")
            Else
                MsgBox("not valid input")
            End If
Thanks for your help
 
You mention both strChars and strText.. are they supposed to be the same thing??

splitting it would be quite messy.

VB.NET:
        Dim [B]strChars[/B] As String = "BCDFGHJKMPQRTVWXY2346789"
 
            Dim numRemain as Integer = searchString.Split(strChars.ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Length
 
            If numRemain = 0 Then
                MsgBox("valid input")
            Else
                MsgBox("not valid input")
            End If

Messy must be a subjective opinion! :D
 
Back
Top