Wildcards and/or Regular Expressions

yablonka

Member
Joined
May 19, 2003
Messages
14
Hi all,

Im 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.

Im trying to mess around with regular expression unsuccesfully.

Anyone?
(A sample code will be very helpful)
Thanks.
 
Last edited by a moderator:
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:

Code:
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.
 

Similar threads

A
Replies
0
Views
120
ACalafiore
A
A
Replies
0
Views
134
ACalafiore
A
W
Replies
0
Views
61
want 2 Learn
W
Back
Top