C# 为什么正则表达式上的For循环比较慢?
我有以下代码:C# 为什么正则表达式上的For循环比较慢?,c#,asp.net-mvc,regex,C#,Asp.net Mvc,Regex,我有以下代码: string pattern = @"(?:\S+\s){1,6}\S*" + search + @"\S*(?:\s\S+){1,6}"; String dbContents = row[2].ToString(); var matches = Regex.Matches(dbContents, pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled); f
string pattern = @"(?:\S+\s){1,6}\S*" + search + @"\S*(?:\s\S+){1,6}";
String dbContents = row[2].ToString();
var matches = Regex.Matches(dbContents, pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
for (int i = 0; i < matches.Count; i++)
{
if (i == 3)
break;
Contents += String.Format("... {0} ...", matches[i].Value);
}
string模式=@“(?:\S+\S){1,6}\S*”+search+@“\S*(?:\S\S+{1,6}”;
字符串dbContents=行[2]。ToString();
var matches=Regex.matches(dbContents,pattern,RegexOptions.IgnoreCase | RegexOptions.Compiled);
for(int i=0;i
我要做的是在搜索词前加一到六个词,在搜索词后加一到六个词。执行代码时,性能会影响for循环“matches.Count”。对于非常大的字符串,执行它需要一分钟以上的时间。我不明白为什么以及如何解决这个问题。为了找到计数,必须找到所有匹配项才能进行计数。考虑到你将在三点后停下来,这似乎有点毫无意义 将
MatchCollection
的惰性计算与来自LINQ的方法结合使用,只进行前三个匹配。通常,在循环中使用StringBuilder
而不是字符串串联也是一个好主意:
StringBuilder builder = new StringBuilder(...);
foreach (var match in matches.Cast<Match>().Take(3))
{
builder.AppendFormat("... {0} ...", matches[i].Value);
}
StringBuilder=新的StringBuilder(…);
foreach(matches.Cast()中的var match.Take(3))
{
AppendFormat(“…{0}…”匹配[i].Value);
}
(StringBuilder的StringBuilder
更改在这里可能不会产生太大的影响,但这是一个好习惯。该方法是必需的,因为Enumerable.Take
仅适用于泛型IEnumerable
类型。)来自MSDN:
Matches
方法使用惰性计算填充返回的
匹配集合对象。访问此集合的成员,例如
MatchCollection.Count和MatchCollection.CopyTo导致收集
立即进行填充。要利用惰性评估,您需要
应该使用中的foreach
等构造来迭代集合
C#
底线:将您的代码更改为使用foreach另一种方法是调用
Match
,然后调用NextMatch
,如下所示:
var match = Regex.Match(dbContents, pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
for (int i = 0; i < 3 && match.Success; i++)
{
Contents += String.Format("... {0} ...", matches[i].Value);
match = match.NextMatch();
}
var match=Regex.match(dbContents,pattern,RegexOptions.IgnoreCase | RegexOptions.Compiled);
对于(int i=0;i<3&&match.Success;i++)
{
Contents+=String.Format(“…{0}…”),匹配[i].Value);
match=match.NextMatch();
}
谢谢!深夜把头撞在墙上。这大大提高了性能。我得到了大约5秒的加载时间,而不是58.67秒。我想你是说第一行的Regex.Match
不是Regex.Matches
?