首页 > 解决方案 > 当 Regex.NextMatch 为空时,程序卡在 NextMatch()

问题描述

我正在尝试解析一个大型 html 文件以提取特定元素,但在解析最后一个元素(Match.NextMatch 为空)之后,它永远不会退出 NextMatch(),代码如下:

Match FrameMatcher = Regex.Match(File.ReadAllText(file.FileName), @"<td class=""tline""><p><a href=""#(.*?)_\[(.*?)]""  style=""font-family:Arial;font-size:10.0pt"">\1 \[\2]<\/a><\/p><\/td>", RegexOptions.Multiline|RegexOptions.Singleline);
                int frameCount = 0;
                while (FrameMatcher.Success)
                {
                    frameCount++;
                    FrameMatcher = FrameMatcher.NextMatch();
                }
                MessageBox.Show(frameCount.ToString());

标签: c#regexfile

解决方案


看起来你有一个无限循环。尝试将 while 条件更改为:

while (FrameMatcher != null)
{
     frameCount++;
     FrameMatcher = FrameMatcher.NextMatch();
}

正如已经提到的,使用 html 解析库而不是正则表达式来解析 html 文件会更好。


推荐阅读