使用正则表达式构造重定向 URL

本文关键字:重定向 URL 正则表达式 | 更新日期: 2023-09-27 18:18:38

如何使用正则表达式重定向示例

exemple.com/en/solution/platform-features

exemple.com/en/platform-features

使用正则表达式构造重定向 URL

如果你的意图是总是删除第三个元素,那么这应该可以做到

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# 中重新加入它