我已经看到了一个如何在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);
}
请解释_exactly_你想达到的目标。特别是投入和想要的产出。 – Oded
基本上,我只是试图编写一个算法,可以应用于给定的字符串,并全局替换所有出现的匹配(使用它的组值)(即贯穿整个字符串)。这太糟糕了,没有可以传递给Replace的“全局”枚举来实现这一点。 –