我想知道是否可以用正則表達式來替換第一個匹配項('[email protected]')中的值('John Doe')下文):正則表達式替換第一個匹配的值
輸入:
Contact: <a href="mailto:[email protected]">John Doe</a>
輸出:
Contact: [email protected]
預先感謝。
我想知道是否可以用正則表達式來替換第一個匹配項('[email protected]')中的值('John Doe')下文):正則表達式替換第一個匹配的值
輸入:
Contact: <a href="mailto:[email protected]">John Doe</a>
輸出:
Contact: [email protected]
預先感謝。
好,我知道它的工作使用MatchEvaluator委託,並命名捕獲:
output = Regex.Replace(input,
@"\<a([^>]+)href\=.?mailto\:(?<mailto>[^""'>]+).?([^>]*)\>(?<mailtext>.*?)\<\/a\>",
m => m.Groups["mailto"].Value);
這將是這樣的。該代碼將在所有的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>
對的,這是可能的。然而,你的例子並不清楚。你用什麼取代哪個部分?據我所知,你只是匹配並返回字符串的一部分,沒有替換。 – 2012-03-10 09:45:59
@AliFerhat我想用電子郵件地址替換姓名(John Doe)。 – Nick 2012-03-10 10:15:54