Wildcards and/or Regular Expressions

yablonka

Newcomer
Joined
May 19, 2003
Messages
14
Hi all,

I'm trying to create a very simple procedure in VB.NET that gets a string and gives back a boolean indicating if the string matches a certain template. For example...

if the string is: abcdefg
and the template is: *cd?f*
(* indicates zero or multiple characters and ? indicates a single character)
then in this case the string does match the template.

I'm trying to mess around with regular expression unsuccesfully.

Anyone?
(A sample code will be very helpful)
Thanks.
 
Last edited:
By using a parser you can build a regular expression from the template.

The template symbol * equals \w* in regex and ? equals \w.

Then try this:

Visual Basic:
Dim Template As String
Dim Pattern As String
Dim SearchString As String
Dim FoundMatch As Boolean
Dim i As Integer
Dim r As Regex

Template = "*cd?f*"
SearchString = "abcdefg"

For i = 0 To Len(Template) - 1
    Select Case Template.Substring(i, 1)
        Case "*"
            Pattern = Pattern + "\w*"
        Case "?"
            Pattern = Pattern + "\w"
        Case Else
            Pattern = Pattern + Template.Substring(i, 1)
    End Select
Next

FoundMatch = r.IsMatch(SearchString, Pattern)

In this case the regex pattern becomes \w*cd\wf\w* and the string matches the template.
 
Back
Top