Jump to content
Xtreme .Net Talk

Recommended Posts

Posted (edited)

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.

Edited by yablonka
  • 2 weeks later...
Posted

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:

 

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.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...