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

问题描述 投票:1回答:2

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

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

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

c# regex regex-group
2个回答
3
投票

解决它的一个简单方法是用贪婪的(.*?)/替换不情愿的([^/]*)

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

如果有一个斜杠,它会在第三个斜杠处停止,如果最终的斜杠不存在,则在字符串的末尾停止。

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

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

1
投票

如果字符包含字母数字,则可以使用以下模式:

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}'");
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.