【问题标题】:Matching optional slash in regex匹配正则表达式中的可选斜杠
【发布时间】:2018-06-05 00:37:25
【问题描述】:

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

我使用这个正则表达式:/.*?/(.*?)/ 但是有时我的网址没有最后一个斜杠,例如 /en/help 由于缺少最后一个斜杠而不匹配。

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

【问题讨论】:

    标签: c# regex regex-group


    【解决方案1】:

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

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

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

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

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

    【讨论】:

      【解决方案2】:

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

      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}'");
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-03-15
        • 1970-01-01
        • 2013-05-15
        • 2012-01-12
        • 2017-05-07
        相关资源
        最近更新 更多