gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 09:08:24 26 4
gpt4 key购买 nike

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

在 php 中有这样的东西:

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

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

最佳答案

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

例如,这个...

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());
}
}
}

关于c# - 有没有办法在正则表达式中执行动态替换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5585357/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com