Regex ISSUE - 无法匹配以任何结尾的URL

时间:2011-04-27 11:52:46

标签: regex url matching

嘿伙计们。我正在尝试使用正则表达式来匹配所有这些URL:

  1. http://example.com
  2. http://example.com/
  3. http://example.com/index.html
  4. http://example.com/index
  5. http://example.com/index/
  6. http://www.example.com
  7. http://www.example.com/
  8. http://www.example.com/index.html
  9. http://www.example.com/index
  10. http://www.example.com/index/
  11. 并匹配包含'#'或'的网址? '直到那两个人之前的角色。 这条路 http://example.com/index.php?p=Hey - > http://example.com/index.php

    到目前为止,我只选择某些文件类型或文件夹(除了一种情况)时,我所使用的正则表达式代码效果很好:

    • 如果我的网址不以文件扩展名(例如:.html,.php)或文件夹(例如:/)结尾,则该模式将无法正确匹配某些网址(例如:{{3} })将被排除在外。

    感谢任何帮助。谢谢大家。


    这是正则表达式:

    ^(?<protocol>http(s?))://(?<domain>[^/\r\n#?]+)(?<path>/[^?#]*(?:html|php|/))?
    

2 个答案:

答案 0 :(得分:1)

不确定您使用的语言是什么,但如果您已经有了一个URL列表,则可能不需要使用正则表达式。

在C#中,您可以这样做:

string a = "http://example.com/index.php?p=Hey";
string b = a.Remove(a.IndexOfAny(new char[] {'?', '#'}, 0));

答案 1 :(得分:1)

这可能会做你想要的:

^(?<protocol>http(s?))://(?<domain>[^/\s#?]+)(?<path>/[^\s#?]*)?(?<query>.*)?

查询将包含您可能想要忽略的其余部分。