有没有办法在正则表达式中执行动态替换?

lui*_*uis 10 c# regex c#-4.0

有没有办法在C#4.0中使用匹配中包含的文本函数进行正则表达式替换?

在PHP中有这样的东西:

reg_replace('hello world yay','(?=')\s(?=')', randomfunction('$0'));
Run Code Online (Sandbox Code Playgroud)

它为每个匹配提供独立的结果,并在找到每个匹配的地方替换它.

Chr*_*ich 11

查看Regex.Replace具有MatchEvaluator过载的方法.这MatchEvaluator是一种方法,您可以指定处理每个匹配项并返回应该用作该匹配项的替换文本的方法.

例如,这......

那只猫跳过了狗.
0:1:CAT跳过2:3:DOG.

...是以下输出:

using System;
using System.Text.RegularExpressions;

namespace MatchEvaluatorTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string text = "The cat jumped over the dog.";
            Console.WriteLine(text);
            Console.WriteLine(Transform(text));
        }

        static string Transform(string text)
        {
            int matchNumber = 0;

            return Regex.Replace(
                text,
                @"\b\w{3}\b",
                m => Replacement(m.Captures[0].Value, matchNumber++)
            );
        }

        static string Replacement(string s, int i)
        {
            return string.Format("{0}:{1}", i, s.ToUpper());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)