2012-10-25 86 views
2

我已经看到了一个如何在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); 
} 
+2

请解释_exactly_你想达到的目标。特别是投入和想要的产出。 – Oded

+0

基本上,我只是试图编写一个算法,可以应用于给定的字符串,并全局替换所有出现的匹配(使用它的组值)(即贯穿整个字符串)。这太糟糕了,没有可以传递给Replace的“全局”枚举来实现这一点。 –

回答

2

您可以通过Replace一个MatchEvaluator。这是一个代表,需要Match并返回要替换的字符串。

例如

string output = re.Replace(
    input, 
    m => "wd" + m.Groups[1].Value + "-" + m.Groups[2].Value); 

或者,和我对此不太确定,你可以使用前瞻 - “检查该文如下,但不包括其在比赛中。”语法是(?=whatver)所以我认为你需要类似word(?=\d-\d)然后用wd替换它。

+0

你的第一个解决方案正是我所希望的!一行代替我的整个'while'循环。谢谢! –

+0

我觉得你对这件事太过分了。问题中没有任何内容或随附的示例代码表明MatchEvaluator是必需的。实际上,他试图解决的问题并不存在:[替换方法](http://msdn.microsoft.com/en-us/library/xwewhkd1.aspx)**为**全局。 –

+0

@Alan我错过了简单使用'$'替换Guffa所显示的内容,但是这里需要_some_形式的反向引用(或向前看)。 – Rawling

4

你不需要做任何逻辑可言,那更换可以在替换字符串中使用组引用来完成:

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