Dot Net Regular Expression Callback

Dot Net Regular Expression Callback

Want to learn how to use regular expression callbacks in dot net languages? The following examples will be using c# for starters but you can easily translate that to vb. Optionally if anyone requests I can translate that to VB and send it.

Dot Net Regular Expression Callback – Details

The heart of the regular expression callback is inside the Regex Class so for starters we need to create the class item. But before that we need some text to modify.

Lets start off with the following text:

This is some sample text for [fname:00000001] [lname:00000001] and also [fname:0000002]. Note that the following: [:fname] and [:lname] will not be replaced.

Ok so from this text, I hope that you can see the replacement items within the text surrounded by [] and containing specific tags. We could perform individual replacements and perform an order of magnitude or replacements, or we could use a callback function to replace to yield somewhat better performance. The performance comes from not having to call replace multiple times.

There is a specific overload of the Regex.replace function that has a parameter called: MatchEvaluator which is basically a delegate to a function which handles the matching processing.

For our purposes I am going to spell out the match pattern for us as follows: @”\[([a-zA-Z]*):([^\]]*)\]”. There are a couple of things to note here. One is the prefix to the string @ which allows us to put single ‘\’ characters to denote an escape, and another is the fact that we have to escape the ‘[‘ and ‘]’ characters respectively. The ‘(‘ and ‘)’ are grouping operators which lets us treat a part of the match specifically and you will see that in the MatchEvaluator function.


About ttessier

Professional Developer and Operator of SwhistleSoft
This entry was posted in Applications Development, Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *