有没有一种方法可以在正则表达式中执行动态替换?

本文关键字:正则表达式 执行 动态 替换 方法 一种 有没有 | 更新日期: 2023-09-27 17:49:01

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

在php中是这样的:

reg_replace('hello world yay','(?=')'s(?=')', randomfunction('$0'));

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

有没有一种方法可以在正则表达式中执行动态替换?

查看具有MatchEvaluator过载的Regex.Replace方法。MatchEvaluator是一个方法,你可以指定处理每个单独的匹配,并返回应该用作该匹配的替代文本。

例如:

猫跳过狗。
1:猫跳过2:狗跳过3:狗。

是以下内容的输出:
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());
        }
    }
}