2013-02-04 48 views
0

我有一個字符串:似乎無法得到這個正則表達式下來

<a href="mailto:[email protected]">Joel Werner</a> 

,我需要剝離一切都關掉,但我的名字

我現在的表情,幾乎做到這一點。

var pattern = new System.Text.RegularExpressions.Regex(">(?<name>.+?)<"); 

但是當我配合他們我得到

>Joel Werner< 

我缺少什麼,因爲我真的不喜歡正則表達式

+1

你可以得到一個名爲捕獲組指出,正則表達式。 –

+2

除非你解析這樣一個非常簡單的字符串,否則我建議使用HTML解析器而不是正則表達式。 – Oded

回答

1

使用羣體得到一致的姓名:

var name = pattern.Match(input).Groups["name"].Value; 

您還可以在引用組之前驗證Success匹配:

var match = pattern.Match(input); 
if (match.Success) 
    name = match.Groups["name"].Value; 

您也可以通過索引Groups[1]參考組。

0

使用這個表達式

<([A-Z][A-Z0-9]*)\b[^>]*>(.*?)</\1> 

然後用第二節比賽,第一場比賽是標籤類型。

1

如果您不喜歡正則表達式,請不要在這種情況下使用它們。用正則表達式解析HTML通常是非常糟糕的。見this answer on why

使用CsQuery

Console.WriteLine(CQ.Create("<a href=\"mailto:[email protected]\">Joel Werner</a>"). //create the selector 
Attr("href"). //get the href attribute 
Split(new char[]{':','@'})[1]); //split it by : and @ and take the second group (after the mailto) 

使用內置在LINQ to XML:

XDocument doc = XDocument.Parse("<a href=\"mailto:[email protected]\">Joel Werner</a>"); 
Console.WriteLine(doc.Element("a").Attribute("href").ToString().Split(new char[] {':', '@'})[1]); 
0
var input = "<a href=\"mailto:[email protected]\">Joel Werner</a>"; 
var pattern = new System.Text.RegularExpressions.Regex(@"<a\shref=""(?<url>.*?)"">(?<name>.*?)</a>"); 
var match = pattern.Match(input); 
var name = match.Groups["name"].Value; 
相關問題