关于如何在涉及组的 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);
}