gpt4 book ai didi

c# - C# Delegate 中的奇怪死循环

转载 作者:行者123 更新时间:2023-11-30 19:28:15 25 4
gpt4 key购买 nike

我已经委托(delegate)处理一些 html 代码。但是我只能匹配第一个匹配。但是 Match 处理程序不会继续。它在第一场比赛中不断循环。谁能告诉我为什么?但是为什么我将匹配 while 循环移到委托(delegate)之外,一切正常。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
namespace migration
{
class Program
{
static void Main(string[] args)
{
string input = "<a class=\"normal\" href=\"http://msdn.microsoft.com/\" title=\"Home\">Home</a><a class=\"active\" href=\"http://msdn.microsoft.com/library/default.aspx\" title=\"Library\">Library</a><a class=\"normal\" href=\"http://msdn.microsoft.com/bb188199\" title=\"Learn\">Learn</a><a class=\"normal\" href=\"http://code.msdn.microsoft.com/\" title=\"Samples\">Samples</a><a class=\"normal\" href=\"http://msdn.microsoft.com/aa570309\" title=\"Downloads\">Downloads</a><a class=\"normal\" href=\"http://msdn.microsoft.com/hh361695\" title=\"Support\">Support</a><a class=\"normal\" href=\"http://msdn.microsoft.com/aa497440\" title=\"Community\">Community</a><a class=\"normal\" href=\"http://social.msdn.microsoft.com/forums/en-us/categories\" title=\"Forums\">Forums</a>";


HTMLStringWalkThrough(input, "<a.+?</a>", "", PrintTest);


}
public static string HTMLStringWalkThrough(string HTMLString, string pattern, string replacement, HTMLStringProcessDelegate p)
{
StringBuilder sb = new StringBuilder();
Match m = Regex.Match(HTMLString, pattern);

while (m.Success)
{
string temp = m.Value;
p(temp, replacement);
m.NextMatch();
}
return sb.ToString();
}
public delegate void HTMLStringProcessDelegate(string input, string replacement);
static void PrintTest(string tag, string replacement)
{
Console.WriteLine(tag);
}
}
}
//output:
//<a class=\"normal\" href=\"http://msdn.microsoft.com/\" title=\"Home\">Home</a>
//<a class=\"normal\" href=\"http://msdn.microsoft.com/\" title=\"Home\">Home</a>
//<a class=\"normal\" href=\"http://msdn.microsoft.com/\" title=\"Home\">Home</a>
//<a class=\"normal\" href=\"http://msdn.microsoft.com/\" title=\"Home\">Home</a>
//<a class=\"normal\" href=\"http://msdn.microsoft.com/\" title=\"Home\">Home</a>
//<a class=\"normal\" href=\"http://msdn.microsoft.com/\" title=\"Home\">Home</a>
//<a class=\"normal\" href=\"http://msdn.microsoft.com/\" title=\"Home\">Home</a>
//.........

最佳答案

您需要分配 Match.NextMatch到你的变量。它返回下一个匹配项,并且不更改当前的 Match:

 m = m.NextMatch();

关于c# - C# Delegate 中的奇怪死循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16282578/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com