[英]Construct redirect URL with RegEx
如何使用Regex進行重定向的示例
exemple.com/en/solution/platform-features
至
exemple.com/en/platform-features
如果您打算始終刪除第三個元素,則應該這樣做
var reg = new Regex(@"(?<Begin>([^/]*/){2})[^/]*/(?<End>.*)");
var match = reg.Match(@"exemple.com/en/solution/platform-features");
var result = match.Groups["Begin"].Value + match.Groups["End"].Value;
您不需要正則表達式; 這只是一個簡單的替換方案。 雖然,為了使其更加靈活,您可以為涉及的部分添加可配置的值,如下所示:
var pattern = ConfigurationManager.AppSettings["pattern"];
var replacement = ConfigurationManager.AppSettings["replacement"];
var url = @"exemple.com/en/solution/platform-features";
var resultUrl = url.Replace(pattern, replacement);
return resultUrl;
並在您的配置文件中放入:
<appSettings>
<add key="pattern" value="/solution/" /> <!--Don't just replace "solution"-it can be another part of the url-->
<add key="replacement" value="/" />
</appSettings>
/([^/]+)(?=/[^/]+/?$)
這個正則表達式將獲得您想要的,但是無論如何,您始終可以將split函數用於/並重新加入c#
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.