2

我在解析为 html 时使用 matchcollection。但这个解决方案需要很长时间,有时会失败。我在想,如果我设置 matchcollection 超时,这个麻烦就会解决。如何设置 matchcollection 的超时?(框架 4.0)

anchorPattern[0]="<div.*?class=\"news\">.*?<div.*?class=\".*?date.*?\">(?<date>.*?)?</div>.*?<a.*?href=\"(?<link>.*?)\".*?>(?<title>.*?)?</a>.*?<(span.*?class=\".*?desc.*?\">(?<spot>.*?)?</span>)?"
    MatchCollection mIcerik = Regex.Matches(html, anchorPattern[i], RegexOptions.Compiled);
    if (mIcerik.Count > 0)
          ListDegree.Add(i,mIcerik.Count);
4

2 回答 2

0

您的正则表达式太多了".*?",对于您的某些输入,可能的组合数量可能接近“无限”。尝试改用原子组"(?>.*?)",以自动丢弃组内任何标记记住的所有回溯位置。这至少会使所有正则表达式解析花费有限的时间。

于 2013-02-08T19:42:30.250 回答
0
TimeSpan timeout = new TimeSpan(0, 1, 0);

anchorPattern[0]="<div.*?class=\"news\">.*?<div.*?class=\".*?date.*?\">(?<date>.*?)?</div>.*?<a.*?href=\"(?<link>.*?)\".*?>(?<title>.*?)?</a>.*?<(span.*?class=\".*?desc.*?\">(?<spot>.*?)?</span>)?"

MatchCollection mIcerik = Regex.Matches(html, anchorPattern[i], RegexOptions.Compiled,timeout);


if (mIcerik.Count > 0)
      ListDegree.Add(i,mIcerik.Count);

Timespan参数建立一个超时间隔以匹配所有对象。或者您可以使用Regex.InfiniteMatchTimeout指示该方法不应超时。 MSDN 正则表达式.Matches()

于 2017-08-01T02:23:09.417 回答