【发布时间】:2018-09-14 03:09:25
【问题描述】:
我有以下用于执行重定向的正则表达式
string requestedPath = HttpUtility.UrlDecode(this.StripLanguage(currentContext.InputUrl.AbsolutePath));
string requestedPathAndQuery = HttpUtility.UrlDecode(currentContext.InputUrl.PathAndQuery);
string requestedRawUrl = HttpUtility.UrlDecode(currentContext.InputUrl.PathAndQuery);
string requestedUrl =
HttpUtility.UrlDecode(
string.Concat(
currentContext.InputUrl.Scheme,
"://",
currentContext.InputUrl.Host,
requestedRawUrl));
string requestedRawUrlDomainAppended = HttpUtility.UrlDecode(currentContext.InputUrl.AbsoluteUri);
string requestedPathWithCulture = HttpUtility.UrlDecode(currentContext.InputUrl.AbsolutePath);
var finalRequestedURL = string.Empty;
finalRequestedURL = Regex.IsMatch(requestedPathAndQuery,matchPattern.Trim(),RegexOptions.IgnoreCase)
? requestedPathAndQuery
: Regex.IsMatch(requestedPath,matchPattern.Trim(),RegexOptions.IgnoreCase)
? requestedPath
: Regex.IsMatch(requestedPathWithCulture,matchPattern.Trim(),RegexOptions.IgnoreCase)
? requestedPathWithCulture
: Regex.IsMatch(requestedRawUrl,matchPattern.Trim(),RegexOptions.IgnoreCase)
? requestedRawUrl
: Regex.IsMatch(requestedUrl,matchPattern.Trim(),RegexOptions.IgnoreCase)
? requestedRawUrlDomainAppended
: string.Empty;
matchPattern 变量是 URL。示例:(.*)/articles/my-article(.*) 应该重定向到 http://www.google.com
正则表达式工作正常,但是当涉及到大量请求时,我们的 CPU 会达到 100%。
有什么办法可以优化上面的吗?
谢谢
【问题讨论】:
-
使用
String.Contains("/articles/my-atricle")并完全跳过regex。 -
有多少个
matchPattern?您可以尝试编译它们并根据模式存储在字典中。将matchPattern.Trim()移动到单独的变量也不能解决问题,但仍然很好。 -
@GuruStron 编译它们是什么意思?对不起菜鸟问题,但我对正则表达式不太熟悉
-
@HishaamNamooya 见this
-
@HishaamNamooya - 我相信这个想法是使用 RegexOptions.Compiled 标志,但只有当你要存储
Regex并重复使用它时才这样做。
标签: c#