2012-09-27 32 views
1

我想在C#中編寫一個函數,用自定義字符串替換正則表達式模式的所有出現。我需要使用匹配字符串來生成替換字符串,所以我想循環而不是使用Regex.Replace()。當我調試我的代碼時,正則表達式模式匹配我的html字符串的一部分,並進入foreach循環,但是,string.Replace函數不會取代匹配。有誰知道是什麼原因導致這種情況發生?C#正則表達式替換使用匹配值

我的功能簡化版本: -

public static string GetHTML() { 
    string html = @" 
     <h1>This is a Title</h1> 
     @Html.Partial(""MyPartialView"") 
    "; 

    Regex ItemRegex = new Regex(@"@Html.Partial\(""[a-zA-Z]+""\)", RegexOptions.Compiled); 
    foreach (Match ItemMatch in ItemRegex.Matches(html)) 
    { 
     html.Replace(ItemMatch.Value, "<h2>My Partial View</h2>"); 
    } 

    return html; 
} 
+0

'string'對象是不可變的,爲了進一步解釋@sethflowers的答案。 – Matthew

+1

你爲什麼使用'Compiled'選項?只有當你有明確的需求時,你才應該使用它。它提供的性能提升並不是很好,它不是免費的。 [ref](http://blogs.msdn.com/b/bclteam/archive/2004/11/12/256783.aspx) –

回答

4

string.Replace返回一個字符串值。你需要把這個分配給你的html變量。請注意,它也會替換匹配值的所有匹配項,這意味着您可能不需要循環。

html = html.Replace(ItemMatch.Value, "<h2>My Partial View</h2>"); 

返回其在 當前實例指定字符串的所有出現與另一指定字符串替換一個新的字符串。

+0

謝謝,當我意識到的時候自己添加了答案,但是你打敗了我。 – user1573618

1

你是不是重新分配到html

這樣:

html = html.Replace(ItemMatch.Value, "<h2>My Partial View</h2>"); 
-2

感覺很無聊。該字符串是不可變的,所以我需要重新創建它。

html = html.Replace(ItemMatch.Value, "<h2>My Partial View</h2>"); 
+0

你不需要重複他人提供的答案。如果它已經解決了你的問題,接受ans! – Anirudha

+0

您可能會注意到發佈之間的小時間間隔。我正在寫我的anwser,而另一個張貼,所以我沒有看到他們。對不起,我沒有接受你的回答我也許沒有很好地問我的問題。 – user1573618

0

至於其他的答案狀態,你是不是分配結果值。

我想補充一點,你的foreach循環沒有多大意義,你可以使用內聯去替換:

Regex ItemRegex = new Regex(@"@Html.Partial\(""[a-zA-Z]+""\)", RegexOptions.Compiled); 
html = ItemRegex.Replace(html, "<h2>My Partial View</h2>"); 
0

這個怎麼樣?那樣的話,你使用比賽的價值取代?

然而,最大的問題是您沒有將替換的結果重新分配給html變量。

using System; 
using System.Text.RegularExpressions; 

namespace ConsoleApplication2 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      var html = @" 
          <h1>This is a Title</h1> 
          @Html.Partial(""MyPartialView"") 
         "; 

      var itemRegex = new Regex(@"@Html.Partial\(""([a-zA-Z]+)""\)", RegexOptions.Compiled); 
      html = itemRegex.Replace(html, "<h2>$1</h2>"); 

      Console.WriteLine(html); 
      Console.ReadKey(); 
     } 
    } 
}