Getting parts of a URL (Regex)

后端 未结 26 2198
说谎
说谎 2020-11-22 02:13

Given the URL (single line):
http://test.example.com/dir/subdir/file.html

How can I extract the following parts using regular expressions:

  1. The Subd
26条回答
  •  有刺的猬
    2020-11-22 02:48

    I tried a few of these that didn't cover my needs, especially the highest voted which didn't catch a url without a path (http://example.com/)

    also lack of group names made it unusable in ansible (or perhaps my jinja2 skills are lacking).

    so this is my version slightly modified with the source being the highest voted version here:

    ^((?Phttp[s]?|ftp):\/)?\/?(?P[^:\/\s]+)(?P((\/\w+)*\/)([\w\-\.]+[^#?\s]+))*(.*)?(#[\w\-]+)?$
    

提交回复
热议问题