gpt4 book ai didi

c# - 正则表达式全局替换为组

转载 作者:行者123 更新时间:2023-12-02 15:38:48 27 4
gpt4 key购买 nike

我四处寻找如何在涉及组的 C# 中实现正则表达式全局替换的示例,但一无所获。所以我自己写了。谁能提出更好的方法来做到这一点?

static void Main(string[] args)
{
Regex re = new Regex(@"word(\d)-(\d)");
string input = "start word1-2 filler word3-4 end";
StringBuilder output = new StringBuilder();
int beg = 0;
Match match = re.Match(input);
while (match.Success)
{
// get string before match
output.Append(input.Substring(beg, match.Index - beg));

// replace "wordX-Y" with "wdX-Y"
string repl = "wd" + match.Groups[1].Value + "-" + match.Groups[2].Value;
// get replacement string
output.Append(re.Replace(input.Substring(match.Index, match.Length), repl));

// get string after match
Match nmatch = match.NextMatch();
int end = (nmatch.Success) ? nmatch.Index : input.Length;
output.Append(input.Substring(match.Index + match.Length, end - (match.Index + match.Length)));

beg = end;
match = nmatch;
}
if (beg == 0)
output.Append(input);
}

最佳答案

您根本不需要执行任何逻辑,可以使用替换字符串中的组引用来完成替换:

string output = Regex.Replace(input, @"word(\d)-(\d)", "wd$1-$2");

关于c# - 正则表达式全局替换为组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13075660/

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