[英]Construct redirect URL with RegEx
How to use Regex for redirecting example 如何使用Regex进行重定向的示例
exemple.com/en/solution/platform-features
to exemple.com/en/solution/platform-features
至
exemple.com/en/platform-features
If your intention is to always remove the third element then this should do it 如果您打算始终删除第三个元素,则应该这样做
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;
You don't need regex for this; 您不需要正则表达式; this is just a simple replace scenario. 这只是一个简单的替换方案。 Although, to make it more flexible you could add configurable values for the involved parts something like this: 虽然,为了使其更加灵活,您可以为涉及的部分添加可配置的值,如下所示:
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;
And in your configuration file just put: 并在您的配置文件中放入:
<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.