Count regex replaces (C#)

前端 未结 3 2025
醉话见心
醉话见心 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条回答
  •  旧时难觅i
    2020-11-30 11:59

    This should do it.

         int count = 0;
         string text = Regex.Replace(text,
              @"(((http|ftp|https):\/\/|www\.)[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?)", //Example expression. This one captures URLs.
              match =>
              {
                   string replacementValue = String.Format("{0}", match.Value);
                   count++;
                   return replacementValue;
              });
    

    I am not on my dev computer so I can't do it right now, but I am going to experiment later and see if there is a way to do this with lambda expressions instead of declaring the method IncrementCount() just to increment an int.

    EDIT modified to use a lambda expression instead of declaring another method.

    EDIT2 If you don't know the pattern in advance, you can still get all the groupings (The $ groups you refer to) within the match object as they are included as a GroupCollection. Like so:

         int count = 0;
         string text = Regex.Replace(text,
              @"(((http|ftp|https):\/\/|www\.)[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?)", //Example expression. This one captures URLs.
              match =>
              {
                   string replacementValue = String.Format("{0}", match.Value);
                   count++;
                   foreach (Group g in match.Groups)
                   {
                        g.Value; //Do stuff with g.Value
                   }
                   return replacementValue;
              });
    

提交回复
热议问题