【问题标题】:Is there a way to perform dynamic replacing in a regular expression?有没有办法在正则表达式中执行动态替换?
【发布时间】:2011-07-31 22:02:09
【问题描述】:

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

在php中有这样的东西:

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

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

【问题讨论】:

    标签: c# regex c#-4.0


    【解决方案1】:

    查看具有MatchEvaluator 重载的Regex.Replace 方法。 MatchEvaluator 是一种方法,您可以指定它来处理每个单独的匹配项并返回应该用作该匹配项的替换文本的内容。

    比如这个……

    猫跳过狗。
    0:THE 1:CAT 跳过 2:THE 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());
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-25
      • 2020-02-23
      • 2019-06-28
      • 2013-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多