有没有办法在正则表达式中执行动态替换? [英] Is there a way to perform dynamic replacing in a regular expression?

查看:443
本文介绍了有没有办法在正则表达式中执行动态替换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一种方法可以在C#4.0中使用匹配中包含的文本的函数来执行regex替换?

Is there a way to do a regex replace in C# 4.0 with a function of the text contained in the match?

在php中有这样的: / p>

In php there is something like this:

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

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

and it gives independent results for each match and replaces it where each match is found.

推荐答案

请参阅 Regex.Replace 方法具有 MatchEvaluator 重载。 MatchEvaluator 是一种方法,您可以指定处理每个匹配,并返回应该用作匹配的替换文本。

See the Regex.Replace methods that have a MatchEvaluator overload. The MatchEvaluator is a method you can specify to handle each individual match and return what should be used as the replacement text for that match.

例如,此...


猫跳过了狗。 :THE 1:CAT跳过2:THE 3:DOG。

The cat jumped over the dog.
0:THE 1:CAT jumped over 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());
        }
    }
}

这篇关于有没有办法在正则表达式中执行动态替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆