我已經看到了一個如何在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的「全局」枚舉來實現這一點。 –