MatchEvaluator 委托

定义

表示此方法,此方法于每次在 Replace 方法操作期间找到单一正则表达式匹配时调用。

C#
public delegate string MatchEvaluator(Match match);
C#
[System.Serializable]
public delegate string MatchEvaluator(Match match);

参数

match
Match

Match 对象表示 Replace 方法操作期间的单个正则表达式匹配。

返回值

MatchEvaluator 委托表示的方法返回的字符串。

属性

示例

下面的代码示例使用 MatchEvaluator 委托将每组匹配的字符替换为匹配项的数目。

C#
using System;
using System.Text.RegularExpressions;

class MyClass
{
   static void Main(string[] args)
   {
      string sInput, sRegex;

      // The string to search.
      sInput = "aabbccddeeffcccgghhcccciijjcccckkcc";

      // A very simple regular expression.
      sRegex = "cc";

      Regex r = new Regex(sRegex);
        
      MyClass c = new MyClass();

      // Assign the replace method to the MatchEvaluator delegate.
      MatchEvaluator myEvaluator = new MatchEvaluator(c.ReplaceCC);
        
      // Write out the original string.
      Console.WriteLine(sInput);

      // Replace matched characters using the delegate method.
      sInput = r.Replace(sInput, myEvaluator);
      
      // Write out the modified string.
      Console.WriteLine(sInput);
   }

   public string ReplaceCC(Match m)
   // Replace each Regex cc match with the number of the occurrence.
   {
      i++;
      return i.ToString() + i.ToString();		
   }
   public static int i=0;
}
// The example displays the following output:
//       aabbccddeeffcccgghhcccciijjcccckkcc
//       aabb11ddeeff22cgghh3344iijj5566kk77

注解

可以使用 MatchEvaluator 委托方法对替换方法(例如 ) Regex.Replace(String, MatchEvaluator)找到的每个匹配项执行自定义验证或操作操作。 对于每个匹配的Replace字符串,该方法使用Match表示匹配项的对象调用MatchEvaluator委托方法。 委托方法执行你喜欢的任何处理,并返回一个字符串,该方法 Replace 替换匹配的字符串。

扩展方法

GetMethodInfo(Delegate)

获取指示指定委托表示的方法的对象。

适用于

产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

另请参阅