我正在编写一个正则表达式并尝试将 URL 的每个部分放入它自己的捕获组中以进行提取:
- 协议(protocol) (http,https)
- 子域 (sub)
- 域 (域)
- 域扩展 (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:协议(protocol)
- Group2:子域(如果存在,如果不存在则留空)
- Group3:域
- Group4:域名后缀
- Group5:目录路径
- Group6:文件名
- Group7:文件扩展名
问题:在我上面列出的所有示例中,如何将每个 URL 部分放入它自己的捕获组?
最佳答案
您可以使用 https://regex101.com/查看组号。
如果您确实关心数字,您始终可以使用“非捕获组 (?:)
(https?):\/\/(?:([\w-]+)\.)?([\w-]+)\.(\w+)((?:\/[\w-]+)*\/)([\w-]+)+\.([\w]+)
那样你确实会得到
第 1 组:协议(protocol)
组 2. 子域
组 3. 域
组 4. 域扩展 (TLD)
组 5./path/to/
第 6 组. 文件名
第 7 组. 扩展
如果有额外的组不打扰你,那么
/(https?):\/\/(([\w-]+)\.)?([\w-]+)\.(\w+)((\/[\w-]+)*\/)([\w-]+)+\.([\w]+)/
你会得到
第 1 组:协议(protocol)
组 3. 子域
第 4 组.域
第 5 组。顶级域(或如您所说的域扩展)
第 6 组。/path/to/
第 8 组. 文件名
第 9 组. 扩展
关于c - 正则表达式 URL 捕获组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39625696/