正则表达式匹配URL前缀

时间:2016-06-11 17:55:33

标签: c# regex url

我正在尝试检索URL的前缀。该URL可能如下所示:

  1. " /索引"
  2. " /索引/"
  3. "?/索引VAR1 =值1"
  4. 我希望能够提取单词" Index"出来的。我对它进行了一次刺杀,但却无法得到它:

    public string GetPrefix(string URL)
            {
                Regex regex = new Regex("^/(.*?)[\\?/]*");
                var matches = regex.Match(URL);
                return matches.Groups[1].ToString();
            }
    

3 个答案:

答案 0 :(得分:2)

尝试:

^/([^/?])+

它匹配/和任何不是/? 1 的字符到 n 次。匹配还会将检索到的前缀存储在捕获组$1中。

答案 1 :(得分:1)

^/(?<action>[^/?#]+)

你必须照顾所有3“/”,“?”和“#”

  1. “/”给出了一个子操作
  2. “?”给出参数
  3. “#”表示页面标记
  4. 此外,您可以命名捕获组以获得更好的注释。

    public string GetPrefix(string url)
    {
        Regex regex = new Regex(@"^/(?<action>[^/?#]+)");
        var match = regex.Match(url);
        return match.Groups["action"].Value;
    }
    

答案 2 :(得分:0)

您可以在此处使用System.Uri命名空间中的System.Web。即使你可能有相对的URL,这应该有效:

using System.Web;
...
var URL = "/Index?var1=value1";
var uri = new Uri(new Uri("http://example.com"), URL); // Init the URI instance
Console.WriteLine(uri.Segments.LastOrDefault().Trim('/'));       // Get the last segment trimming any slashes

请参阅IDEONE demo

相关问题