簡體   English   中英

正則表達式用第一個匹配項替換值

[英]Regex replace value with first match

我想知道正則表達式是否可以用第一個匹配項(以下示例中的“ test@tester.com”)替換值(以下示例中的“ John Doe”):

輸入:

Contact: <a href="mailto:test@tester.com">John Doe</a>

輸出:

Contact: test@tester.com

提前致謝。

就像這樣。 該代碼將在所有mailto鏈接中用電子郵件替換名稱:

var html = new StringBuilder("Contact: <a href=\"mailto:test1@tester1.com\">John1 Doe1</a> <a href=\"mailto:test2@tester2.com\">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:test1@tester1.com">test1@tester1.com</a> <a href="mailto:test2@tester2.com">test2@tester2.com</a>

好的,使用MatchEvaluator委托和命名捕獲使其工作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM