The regular expression engine in .NET is obviously a powerful alternative to traditional String manipulation methods when dealing with complex parsing or validation. The power of the Regex.Replace method allows the developer to perform replacements based on patterns rather than literal text. Beyond this, though, .NET Regex offers an even more powerful tool - the MatchEvaluator.
A MatchEvaluator is simply a pointer to a function that takes a Match as its only parameter and returns a String. When calling Regex.Replace, you can then pass the MatchEvaluator instead of a replacement string, and .NET will call your MatchEvaluator and then use the returned Strnig as the result of the Replace. This offers the ability to perform complex parsing withing a call to Replace, including the ability to reference other methods and classes. One common example is an expression evaluator. You may want to replace the String "3*2" with "6" in an expression. The following code shows how to do this simple example using a MatchEvaluator:
| Public Function EvaluateString(ByVal s As String) As String Dim MatchEval As New MatchEvaluator(AddressOf RegexReplaceEvaluator) Dim Pattern As String = "(?<param1>\d+)(?<sign>\+|-|/|\*)(?<param2>\d+)" Return Regex.Replace(s, Pattern, MatchEval) End Function Public Function RegexReplaceEvaluator(ByVal m As Match) As String Select Case m.Groups("sign").Value Case "+" Return (CInt(m.Groups("param1").Value) + _ CInt(m.Groups("param2").Value)).ToString Case "-" Return (CInt(m.Groups("param1").Value) - _ CInt(m.Groups("param2").Value)).ToString Case "/" Return (CInt(m.Groups("param1").Value) / _ CInt(m.Groups("param2").Value)).ToString Case "*" Return (CInt(m.Groups("param1").Value) * _ CInt(m.Groups("param2").Value)).ToString Case Else Return "ERROR" End Select End Function |
| Return Regex.Replace(s, Pattern, AddressOf RegexReplaceEvaluator) |