所以我的网址看起来像:
/hello-world/blah/
/hello-world/blah
/hello-world/blah/234
/hello-world/234
Run Code Online (Sandbox Code Playgroud)
如果url后面有数字后跟斜杠,我需要返回相同的字符串,但删除了斜杠和数字.
所以最后两行现在应该是这样的:
/hello-world/blah
/hello-world
Run Code Online (Sandbox Code Playgroud)
如何获得所有内容但是尾部斜线和数字(如果它们存在)
怎么样:
url = Regex.Replace(url, @"/\d*$", "");
Run Code Online (Sandbox Code Playgroud)
注意$ here,这意味着斜杠和数字必须位于字符串的末尾.这将阻止它们从URL中间删除,如以下测试所示:
using System;
using System.Text.RegularExpressions;
public class Test
{
static void Main()
{
TestUrl("/hello-world/blah/");
TestUrl("/hello-world/blah/234");
TestUrl("/hello-world/234");
TestUrl("/hello-world/234/blah");
TestUrl("/hello-world/12/34");
}
static void TestUrl(string url)
{
string transformed = Regex.Replace(url, @"/\d*$", "");
Console.WriteLine("{0} => {1}", url, transformed);
}
}
Run Code Online (Sandbox Code Playgroud)
结果:
/hello-world/blah/ => /hello-world/blah
/hello-world/blah/234 => /hello-world/blah
/hello-world/234 => /hello-world
/hello-world/234/blah => /hello-world/234/blah
/hello-world/12/34 => /hello-world/12
Run Code Online (Sandbox Code Playgroud)
编辑:我不希望这是你的代码中的瓶颈.您可能想要创建一次正则表达式,并重用它:
private static readonly Regex TrailingSlashAndDigits =
new Regex(@"/\d*$", RegexOptions.Compiled);
Run Code Online (Sandbox Code Playgroud)
然后使用
url = TrailingSlashAndDigits.Replace(url, "");
Run Code Online (Sandbox Code Playgroud)
您可以尝试IsMatch先使用,但我怀疑它会产生很大的困难 - 如果您发现这是一个瓶颈,我肯定只会达到额外的复杂程度.除非你的代码除了这个之外没什么用,否则我怀疑情况会是这样.
| 归档时间: |
|
| 查看次数: |
1570 次 |
| 最近记录: |