简体   繁体   中英

Regex replace value with first match

I was wondering if something like this is possible with Regex, to replace a value ('John Doe' in my example below) with the first match ('test@tester.com' in my example below):

Input:

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

Output:

Contact: test@tester.com

Thanks in advance.

It would be something like this. The code will replace names with e-mails in all mailto links:

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);

Output:

Contact: <a href="mailto:test1@tester1.com">test1@tester1.com</a> <a href="mailto:test2@tester2.com">test2@tester2.com</a>

Ok, got it working using MatchEvaluator delegate and named captures:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM