Using a MatchEvaluator with Regex.Replace

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:

+展开
-VBScript
   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 



This is a simplified example, but it shows how a MatchEvaluator can be used to perform operations that would be much more complex with standard parsing methods. For those who want to realize the full power of the MatchEvaluator, check out Chapter 12 of Francesco Balena's book, Programming Visual Basic .NET, in which he offers code that will evaluate complex expressions with nested levels of parentheses, logarithmic functions, and trigonometric functions.

Note also that you do not need to declare a MatchEvaluator object. The Regex.Replace method will also take a delegate within the call itself like this:

+展开
-VBScript
Return Regex.Replace(s, Pattern, AddressOf RegexReplaceEvaluator)


加支付宝好友偷能量挖...


评论(0)网络
阅读(104)喜欢(0)Asp.Net/C#/WCF