匹配正则表达式中的可选斜线

Matching optional slash in regex

我需要一个正则表达式来匹配 url 中三个“/”字符之间的前两个词:例如。在 /en/help/test/abc/def 中,它应该匹配 /en/help/。

我使用这个正则表达式:/.*?/(.*?)/ 但是有时我的 url 没有最后一个斜线,比如 /en/help 因为缺少最后一个斜线而不匹配。

你能帮我调整正则表达式只匹配“/en/help”部分吗?谢谢

一个简单的解决方法就是把reluctive (.*?)/换成greedy ([^/]*):

/.*?/([^/]*)

如果有第三个斜杠,这将在第三个斜杠处停止,如果没有最后一个斜杠,则在字符串末尾停止。

请注意,为了保持一致性,您可以将 .*? 替换为相同的 [^/]* 表达式:

/[^/]*/([^/]*)

如果字符将包含字母数字,那么您可以使用以下模式:

static void Main(string[] args)
{
    string s1 = "/en/help/test/abc/def";
    string s2 = "/en/help ";
    string pattern = 
        @"(?ix)   #Options
          /       #This will match first slash
          \w+     #This will match [a-z0-9]
          /       #This will match second slash
          \w+     #Finally, this again will match [a-z0-9] until 3-rd slash (or end)";
    foreach(string s in new[] { s1, s2})
    {
        var match = Regex.Match(s, pattern);
        if (match.Success) Console.WriteLine($"Found: '{match.Value}'");
    }
}