Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Regex替换为命名组和周围的所有内容_C#_Regex - Fatal编程技术网

C# Regex替换为命名组和周围的所有内容

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"> 使用捕获组也可以捕获标记的其他部分:

想象一下,我有一个正则表达式,它应该捕获一个HTML链接并用另一个链接替换它

正则表达式看起来像这样:

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