2012-03-10 177 views
1

我想知道是否可以用正則表達式來替換第一個匹配項('[email protected]')中的值('John Doe')下文):正則表達式替換第一個匹配的值

輸入:

Contact: <a href="mailto:[email protected]">John Doe</a> 

輸出:

Contact: [email protected] 

預先感謝。

+2

對的,這是可能的。然而,你的例子並不清楚。你用什麼取代哪個部分?據我所知,你只是匹配並返回字符串的一部分,沒有替換。 – 2012-03-10 09:45:59

+0

@AliFerhat我想用電子郵件地址替換姓名(John Doe)。 – Nick 2012-03-10 10:15:54

回答

0

好,我知道它的工作使用MatchEvaluator委託,並命名捕獲:

output = Regex.Replace(input, 
    @"\<a([^>]+)href\=.?mailto\:(?<mailto>[^""'>]+).?([^>]*)\>(?<mailtext>.*?)\<\/a\>", 
    m => m.Groups["mailto"].Value); 
1

這將是這樣的。該代碼將在所有的mailto鏈接替換電子郵件名稱:

var html = new StringBuilder("Contact: <a href=\"mailto:[email protected]\">John1 Doe1</a> <a href=\"mailto:[email protected]\">John2 Doe2</a>"); 

var regex = new Regex(@"\<a href=\""mailto:(?<email>.*?)\""\>(?<name>.*?)\</a\>"); 
var matches = regex.Matches(html.ToString()); 

foreach (Match match in matches) 
{ 
    var oldLink = match.Value; 
    var email = match.Groups["email"].Value; 
    var name = match.Groups["name"].Value; 
    var newLink = oldLink.Replace(name, email); 
    html = html.Replace(oldLink, newLink); 
} 

Console.WriteLine(html); 

輸出:

Contact: <a href="mailto:[email protected]">[email protected]</a> <a href="mailto:[email protected]">[email protected]</a> 
+0

不幸的是,我確實需要「注入」匹配,而不是構造一個新的字符串,因爲輸入是一個大字符串,其中的文本超出了我在示例中指定的範圍。 – Nick 2012-03-10 10:14:36

+0

@Nick,我理解你有一個可以包含許多「mailto」鏈接的HTML頁面,並且你想要全部替換它們嗎? – 2012-03-10 10:24:50

+0

是的,該頁面包含HTML。 – Nick 2012-03-10 10:30:45

相關問題