Warm tip: This article is reproduced from serverfault.com, please click

Getting parts of a URL (Regex)

发布于 2008-08-26 11:01:37

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 Subdomain (test)
  2. The Domain (example.com)
  3. The path without the file (/dir/subdir/)
  4. The file (file.html)
  5. The path with the file (/dir/subdir/file.html)
  6. The URL without the path (http://test.example.com)
  7. (add any other that you think would be useful)

The regex should work correctly even if I enter the following URL:

http://example.example.com/example/example/example.html
Questioner
pek
Viewed
0
community wiki 2015-04-26 03:17:33

A single regex to parse and breakup a full URL including query parameters and anchors e.g.

https://www.google.com/dir/1/2/search.html?arg=0-a&arg1=1-b&arg3-c#hash

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

RexEx positions:

url: RegExp['$&'],

protocol:RegExp.$2,

host:RegExp.$3,

path:RegExp.$4,

file:RegExp.$6,

query:RegExp.$7,

hash:RegExp.$8

you could then further parse the host ('.' delimited) quite easily.

What I would do is use something like this:

/*
    ^(.*:)//([A-Za-z0-9\-\.]+)(:[0-9]+)?(.*)$
*/
proto $1
host $2
port $3
the-rest $4

the further parse 'the rest' to be as specific as possible. Doing it in one regex is, well, a bit crazy.