简体   繁体   English

正则表达式用第一个匹配项替换值

[英]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): 我想知道正则表达式是否可以用第一个匹配项(以下示例中的“ test@tester.com”)替换值(以下示例中的“ John Doe”):

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: 该代码将在所有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);

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: 好的,使用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