好的,我的问题是关于检查性能
假设我有以下正则表达式
regex1 = "=powered\ by\ 4images"
regex2 = "post\ comment"
regex3 = "kommentar\ posten"
regex4 = "\[url=.*?.*?.*?.*?://"
string mystring="";
现在我想要的是这个
if( Regex.IsMatch(srinput, regex1 , RegexOptions.IgnoreCase)
&& Regex.IsMatch(srinput, regex2 , RegexOptions.IgnoreCase)
&& (Regex.IsMatch(srinput, regex3 , RegexOptions.IgnoreCase)
|| Regex.IsMatch(srinput, regex4 , RegexOptions.IgnoreCase)))
那么这会使每个选项对字符串文本进行全扫描查询吗?
无论如何,这可以加紧吗?我不知道在一次迭代中检查所有正则表达式等?
这是实现多个正则表达式IsMatch检查的最佳性能吗?
c#.net 4.5.2 wpf application
答案 0 :(得分:4)
您可以使用positive lookahead assertions模拟布尔AND(&&
)和alternation来模拟正则表达式中的布尔OR(||
)。
然后,您不需要在正则表达式中转义空格字符,但如果您希望它与字面点匹配,则应该转义该点。我认为你的意思是这样的:
Regex regex1 = new Regex(@"
^ # Either make sure that at the start of the string
(?=.*=powered by 4images) # it's possible to match this subregex
(?=.*post comment) # and this one
(?=.*kommentar posten) # and this one
| # or
\[url=.*?\..*?\..*?\..*?:// # match this regex anywhere in the string",
RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
答案 1 :(得分:1)
静态Regrex.IsMatch在内部调用return new Regex(pattern, options, matchTimeout, true).IsMatch(input);
如果你执行了很多检查,并且可能创建一个实例并重复使用它将节省一些性能。这是代码:
string mystring = "MonsterMMORPG";
var sw = new Stopwatch();
sw.Start();
int count = 10000;
var regex1 = @"=powered\ by\ 4images";
for (int i = 0; i < count; i++)
{
if (Regex.IsMatch(mystring, regex1, RegexOptions.IgnoreCase))
{
}
}
sw.Stop();
Console.WriteLine(string.Format("using Static Check:{0}", sw.Elapsed));
sw = new Stopwatch();
var r = new Regex(regex1,RegexOptions.IgnoreCase);
sw.Start();
for (int i = 0; i < count; i++)
{
if (r.IsMatch(mystring))
{
};
}
sw.Stop();
Console.WriteLine(string.Format("using instance Check:{0}", sw.Elapsed));
输出是: 使用静态检查:00:00:00.0074411 使用实例检查:00:00:00.0006221
无论哪种方式,regrex检查都非常快,但实例1的速度稍快一些答案 2 :(得分:1)
只需在正则表达式的每个条件之间添加|
,然后立即匹配。
(=powered\ by\ 4images)|(post\ comment)|(kommentar\ posten)|(\[url=.*?.*?.*?.*?:)