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

language agnostic-获取URL的一部分(正则表达式)

(language agnostic - Getting parts of a URL (Regex))

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

给定URL(单行):http :
//test.example.com/dir/subdir/file.html

如何使用正则表达式提取以下部分:

  1. 子域(测试)
  2. 域(example.com)
  3. 没有文件的路径(/ dir / subdir /)
  4. 文件(file.html)
  5. 文件的路径(/dir/subdir/file.html)
  6. 不含路径的网址(http://test.example.com
  7. (添加你认为有用的其他任何内容)

即使我输入以下URL,该正则表达式也应能正常工作:

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

单个正则表达式可解析和分解包括查询参数和锚点的完整URL,例如

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职位:

网址:RegExp ['$&'],

协议:RegExp。$ 2,

主持人:RegExp。$ 3,

路径:RegExp。$ 4,

文件:RegExp。$ 6,

查询:RegExp。$ 7,

hash:RegExp。$ 8

然后,你可以轻松地进一步解析主机(以“。”定界)。

什么会做的是使用这样的:

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

进一步分析“其余”尽可能具体。在一个正则表达式中这样做有点疯狂。