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

时间:2012-03-10 09:40:20

标签: c# regex

我想知道Regex是否可以这样做,用第一场比赛替换一个值(下面我的例子中的'John Doe')(在下面的例子中为'test@tester.com'):

输入:

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

输出:

Contact: test@tester.com

提前致谢。

2 个答案:

答案 0 :(得分:1)

会是这样的。该代码将在所有 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>

答案 1 :(得分:0)

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

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