我想知道是否可以用正则表达式来替换第一个匹配项('[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