3

我正在编写一个正则表达式并尝试将 URL 的每个部分放入它自己的捕获组中以进行提取:

  • 协议 (http、https)
  • 子域 (子)
  • (域)
  • 域名扩展 (com,net)
  • 路径 (/path/to/file - 这是文件所在目录的路径)
  • URI (文件名)
  • URI 扩展 名(文件扩展名 - js、css、pdf)

示例网址:

http://domain.com/path1/to/file.js
http://domain.com/path-dash/to-dash/file.js
http://domain.com/path-dash/to-dash/file-name.js
https://sub.domain.com/path/to/file.js
http://sub.domain-dash.net/path/to/file.js
http://sub-dash.domain.com/path/to/file.js
http://sub-dash.domain-dash.com/path/to/file.js

到目前为止我所拥有的:

/(https?):\/\/(\w+[\-]?\w+)?.?(\w+[\-]?\w+)?/gm

期望的输出:

  • Group1:协议
  • Group2:子域(如果存在,如果不存在,则为空白)
  • Group3:
  • Group4:域扩展
  • Group5:目录路径
  • Group6:文件名
  • Group7:文件扩展名

问题:如何在上面列出的所有示例中将每个 URL 部分放入它自己的捕获组中?

4

1 回答 1

2

您可以使用https://regex101.com/查看组号。

如果您确实关心数字,则可以始终使用“非捕获组 (?:)

(https?):\/\/(?:([\w-]+)\.)?([\w-]+)\.(\w+)((?:\/[\w-]+)*\/)([\w-]+)+\.([\w]+)

这样你确实会得到

第一组:协议

组 2. 子域

组 3. 域

组 4. 域扩展 (TLD)

第 5 组。/path/to/

组 6. 文件名

组 7. 扩展


如果有额外的团体不会打扰你,那么

/(https?):\/\/(([\w-]+)\.)?([\w-]+)\.(\w+)((\/[\w-]+)*\/)([\w-]+)+\.([\w]+)/

你会得到

第一组:协议

组 3. 子域

组 4. 域

第 5 组。顶级域(或如您所说的域扩展)

第 6 组。/path/to/

组 8. 文件名

组 9. 扩展

于 2016-09-21T20:34:56.823 回答