This is the second time I have had to do something like this. So this time I am posting it for my reference. Regular expressions are amazing and amazingly difficult to understand sometimes, but they come in very handy. I was in a situation where I was going to need to feed in a custom template to be used similar to a “mail merge” situation. I would query a database, then for each record I would fill out an email using an email template. I decided to go with <:FieldName:> as the nomenclature of how a field would be inserted. For example, here are the query results:
| FirstName | LastName | Company |
| Eric | Bridges | DataBatrix |
My email template may look something like this:
Dear <:FirstName:> <:LastName:>,
You work for <:Company:>!
For the purpose of my project, I did not know what fields were going to be returned or what the email template looked like. I needed a simple way to replace all of the field placeholders with actual data. Regular expressions to the rescue! You can use a delegate to run your own replace function. I called my method MatchHandler which is passed a Match variable (the match that is found). In my example below, I replaced it with the corresponding item from _reader (my sqldatareader row).
Private Function MatchHandler(ByVal m As Match) As String
Dim fieldName As String = m.Groups("fieldName").ToString()
If HasField(fieldName) Then
Return _reader(fieldName)
Else
Return m.ToString()
End If
End Function
Next we have to create our delegate. Delegates are basically pointers for methods (functions/subs). I called my delegate “MatchDelegate” and pass it the address of my function I created above.
Dim MatchDelegate As New MatchEvaluator(AddressOf MatchHandler)
Now to make it work! Define your regular expression pattern and instantiate a new RegularExpression object. Use the Replace method and pass the string to search and the delegate that we created.
Private Function MergeFields(ByVal body As String) As String
Dim returnValue As String = ""
Dim pattern As String = "<:(?<fieldName:>(.+?)):>"
Dim regex As New Text.RegularExpressions.Regex(pattern)
returnValue = regex.Replace(body, MatchDelegate)
Return returnValue
End Function
That’s it! Now you can do whatever you like when a match is found in your Replace method.
In case you were wondering what “(?<fieldName:>(.+?))” in the pattern was all about, check out this link talking about regular expression groups.




