C# Regex替换为命名组和周围的所有内容
想象一下,我有一个正则表达式,它应该捕获一个HTML链接并用另一个链接替换它 正则表达式看起来像这样:C# Regex替换为命名组和周围的所有内容,c#,regex,C#,Regex,想象一下,我有一个正则表达式,它应该捕获一个HTML链接并用另一个链接替换它 正则表达式看起来像这样: <a.+?href="(?'url'.+?)".*?> <a href="http://www.google.com"> 我将在命名组中获得一个参数匹配 但是Match.Groups集合不仅仅包含3项 我怎么把整个比赛重新组合起来,结果会是 <a href="http://www.EvulRulz.devil"> 使用捕获组也可以捕获标记的其他部分:
<a.+?href="(?'url'.+?)".*?>
<a href="http://www.google.com">
我将在命名组中获得一个参数匹配
但是Match.Groups集合不仅仅包含3项
我怎么把整个比赛重新组合起来,结果会是
<a href="http://www.EvulRulz.devil">
使用捕获组也可以捕获标记的其他部分:
()”;
var-str=@;
var newUrl=”http://www.stackoverflow.com";
var newTag=Regex.Replace(str,模式,“$1”+newUrl+“$3”);
(我对基本正则表达式做了一些更改)我坚持使用MatchEvaluator重载,因为实际上我需要做更多的工作,但现在我已经理解了组索引的含义。因此,我的代码看起来更像:match.Groups[1]。Value+“EvulRulz.devil”+match.Groups[3]。Value
regex.Replace(new MatchEvaluator(ReplaceUrl))
<a href="http://www.EvulRulz.devil">
private static String ReplaceUrl(Match match)
{
return (match.Groups[1].Value + "http://www.EvulRulz.devil" + match.Groups[2].Value);
}
var pattern = @"(<a.+?href="")([^""]+)(""[^>]*>)";
var str = @"<a target=""_blank"" href=""#top"">";
var newUrl = "http://www.stackoverflow.com";
var newTag = Regex.Replace(str, pattern, "$1" + newUrl + "$3");