Count regex replaces (C#)

前端 未结 3 2022
醉话见心
醉话见心 2020-11-30 10:55

Is there a way to count the number of replacements a Regex.Replace call makes?

E.g. for Regex.Replace(\"aaa\", \"a\", \"b\"); I want to get the number 3

3条回答
  •  自闭症患者
    2020-11-30 11:54

    You can use a MatchEvaluator that runs for each replacement, that way you can count how many times it occurs:

    int cnt = 0;
    string result = Regex.Replace("aaa", "a", m => {
      cnt++;
      return "b";
    });
    

    The second case is trickier as you have to produce the same result as the replacement pattern would:

    int cnt = 0;
    string result = Regex.Replace("aaa", "(?aa?)", m => {
      cnt++;
      return m.Groups["test"] + "b";
    });
    

提交回复
热议问题