2014-02-25 42 views
1

我有一個示例代碼用正則表達式的開始和結束串

<h1> 
    <asp:Literal ID="ltAccountTitle" runat="server"></asp:Literal> 
</h1> 
<p> 
    <asp:Literal ID="ltNetBalance" runat="server" Text="Net balance" meta:resourcekey="ltNetBalanceResource"></asp:Literal> 
    <span> 
     <asp:Literal ID="ltNetBalanceAmount" runat="server"></asp:Literal> 
    </span> 
</p> 

我想寫一個正則表達式找到一個長字符串中的字符串。

匹配:

<asp:Literal ID="ltAccountTitle" runat="server"></asp:Literal> 

<asp:Literal ID="ltNetBalanceAmount" runat="server"></asp:Literal> 

其實我使用下面的代碼來獲取所有匹配到的字符串列表。用哪個正則表達式我可以得到它?我已經嘗試了許多模式變量的事情,但無法解決這個問題。

var lst = new List<string>(); 
var mcol = Regex.Matches(text2, pattern); 

foreach (Match m in mcol) 
{ 
    lst.Add(m.Value); 
} 
+1

只是建議得到:代替正則表達式檢查http://htmlagilitypack.codeplex.com/ – Cynede

+4

我不知道你想要捕獲什麼。你能提供一個例子嗎? – Hegi

+0

+1爲'HtmlAgilityPack';正則表達式通常是解析HTML的一個糟糕的選擇 – decPL

回答

0

你試圖讓只有具有ID和RUNAT服務器標籤的文字,如果是下面的工作正常,我和正好2個文字

static void TestRegEx() 
{ 
    string input = "<h1>" 
     + "<asp:Literal ID=\"ltAccountTitle\" runat=\"server\"></asp:Literal>" 
     + "</h1>" 
     + "<p>" 
     + "<asp:Literal ID=\"ltNetBalance\" runat=\"server\" Text=\"Net balance\" meta:resourcekey=\"ltNetBalanceResource\"></asp:Literal>" 
     + "<span>" 
     + "<asp:Literal ID=\"ltNetBalanceAmount\" runat=\"server\"></asp:Literal>" 
     + "</span>" 
     + " </p>"; 

    var collection = Regex.Matches(input, "<asp:Literal ID=\"\\w*\" runat=\"server\"></asp:Literal>"); 

    foreach (Match item in collection) 
    { 
     Console.WriteLine(item.Value); 
    } 

}

相關問題