2009-10-22 127 views
0

我有下面的代碼:正則表達式替換和替換字符串

Regex.Replace(text, words.ToString(), "<dfn title=\"" + this.FindDefinition("$0") + "\">$0</dfn>", RegexOptions.IgnoreCase | RegexOptions.Compiled); 

我遇到的問題是與FindDefinition方法。我想發送原始單詞進行查找並返回定義文本。這是可能的還是我需要創建一個這樣的模板:

Regex.Replace(text, words.ToString(), "<dfn title=\"{$0}\">$0</dfn>", RegexOptions.IgnoreCase | RegexOptions.Compiled); 

然後做一個搜索它來取代它與我的定義?

我也試過用:

Regex.Replace(text, words.ToString(), this.ReplaceWord, RegexOptions.IgnoreCase | RegexOptions.Compiled); 

private string ReplaceWord(Match m) 
{ 
    return "<dfn title=\"" + this.FindDefinition(m.Value) + "\">$0</dfn>"; 
} 

它與FindDefinition方法工作得很好,但後來我有一個問題讓原始值。

我錯過了什麼?

回答

0

試試這個:

return string.Format("<dfn title=\"{0}\">{1}</dfn>", 
        this.FindDefinition(m.Value), 
        m.Value); 
+0

你當然是對的..當我早些時候測試這個時,我一定犯了錯誤。謝謝 :)。 – 2009-10-22 08:53:30

0

你正在構建的手XML,它幾乎總是錯誤的。

您需要使用評估程序(replaceword)。你爲什麼不這樣做:

private string ReplaceWord(Match m) 
{ 
    return "<dfn title=\"" + this.FindDefinition(m.Value) + "\">"+m.Value+"</dfn>"; 
} 

我傾向於使用類似m.Groups [0] .value的,並使用正則表達式中的分組。