我创建了一个演示应用程序来测试某些正则表达式的性能。我的第三个测试使用选项RightToLeft。
看来它大大加快了流程!为什么?它有什么作用?
这是我的测试应用程序:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
private const string IsRequestForDirectoryWithoutTrailingSlashRegex = @"^(?#Path:)(.*/)?(?#LastPart:)(?<!\.asmx|\.aspx/)([^./?#]+?)(?#QueryString:)(\?.*?)(?#Anchor:)?(#.*)?$";
private static string[] Tests = new string[] {
"http://localhost/manager/page.aspx",
"http://localhost/manager/",
"http://localhost/manager",
"http://localhost/manager/?param=value",
"http://localhost/manager/dir?param=value"
};
static void Main(string[] args)
{
Test1();
Test2();
Test3();
Test4();
Console.WriteLine();
Console.ReadLine();
}
public static void Test1()
{
Regex regex = new Regex(IsRequestForDirectoryWithoutTrailingSlashRegex);
DoWork("1", regex);
}
public static void Test2()
{
Regex regex = new Regex(IsRequestForDirectoryWithoutTrailingSlashRegex, RegexOptions.Compiled);
DoWork("2", regex);
}
public static void Test3()
{
Regex regex = new Regex(IsRequestForDirectoryWithoutTrailingSlashRegex, RegexOptions.Compiled | RegexOptions.RightToLeft);
DoWork("3", regex);
}
public static void Test4()
{
Regex regex = new Regex(IsRequestForDirectoryWithoutTrailingSlashRegex, RegexOptions.Compiled | RegexOptions.RightToLeft | RegexOptions.IgnoreCase);
DoWork("4", regex);
}
static void DoWork(string name, Regex regex)
{
Stopwatch sp = new Stopwatch();
sp.Start();
for (int i = 0; i < 100000; i++)
{
foreach (string s in Tests)
{
regex.IsMatch(s);
}
}
foreach (string s in Tests)
{
Console.WriteLine(":" + s + ":" + regex.IsMatch(s).ToString());
}
sp.Stop();
Console.WriteLine("Test " + name + ": " + sp.ElapsedTicks);
}
}
}
该RegexOptions.RightToLeft
可当你要匹配你希望找到输入字符串的结尾,一个模式非常有用,因为它的文档说:从搜索去右到左 从输入字符串的最后一个字符开始,从左到右,虽然regex本身仍然从左到右应用。
您的正则表达式似乎正在寻找目录路径的尾部斜杠,因此这似乎是符合说明的情况。
尽管您的表达式正在寻找斜杠,但是这两个锚点(^
和$
)的存在使我的推理错了,因为正则表达式无论从何处开始都只能以一种可能的方式进行匹配。
我将继续寻找导致此问题的实际原因,但现在我将保持原样。
另一方面,在.*/
表达式(?#Path:)
开始部分之后的表达式部分将消耗整个输入字符串,然后每次都递归返回以查找最后一个字符串/
,因此,在更远的位置开始搜索时,可能没有很多回溯。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句