正则表达式 - 获取 URL 协议、主机、路径,但不是文件名 - PCRE
Regex - get URL protocol, host, path, but not filename - PCRE
目标
替换主机和路径(位置),但保留文件名(它们没有改变)。
URL 没有子域 - 不起作用
这适用于至少有一个子域(例如 'www.somedomain.com')的主机(域),但无法获得仅包含域 + TLD 的路径(例如 'somedomain.com')
(http[s]?:\/\/([^:\/\s]+)(\/\w+)*\/)+
在下面的 HTML 片段中
junk before tag <img src="https://somedomain.com/wp-content/uploads/2017/10/someimage.jpg" alt="" />Random text after
PCRE 引擎只会捕获:
https://somedomain.com/
URL with 子域 - 有效
在以下 HTML 片段中(域有一个子域)
junk before tag <img src="https://www.somedomain.com/wp-content/uploads/2017/10/someimage.jpg" alt="" />Random text after
PCRE 引擎捕获整个 URL(保存为文件):
https://www.somedomain.com/wp-content/uploads/2017/10/
问题
如何调整正则表达式以捕获 [=16= 的完整协议、域 和路径 (但不是文件名) ] URL 有子域 以及 那些 没有 子域?
https?:\/\/(?:[^\/ ]*\/)*
演示 here.
说明
http //Should start with http
s? // s is optional
:\/\/ // should follow up with ://
(?: //START Non capturing group
[^\/ ]* //Any character but a / or a space
\/ //Ends with /
) //END Non capturing group
* //Repeat non-capturing group
目标
替换主机和路径(位置),但保留文件名(它们没有改变)。
URL 没有子域 - 不起作用
这适用于至少有一个子域(例如 'www.somedomain.com')的主机(域),但无法获得仅包含域 + TLD 的路径(例如 'somedomain.com')
(http[s]?:\/\/([^:\/\s]+)(\/\w+)*\/)+
在下面的 HTML 片段中
junk before tag <img src="https://somedomain.com/wp-content/uploads/2017/10/someimage.jpg" alt="" />Random text after
PCRE 引擎只会捕获:
https://somedomain.com/
URL with 子域 - 有效
在以下 HTML 片段中(域有一个子域)
junk before tag <img src="https://www.somedomain.com/wp-content/uploads/2017/10/someimage.jpg" alt="" />Random text after
PCRE 引擎捕获整个 URL(保存为文件):
https://www.somedomain.com/wp-content/uploads/2017/10/
问题
如何调整正则表达式以捕获 [=16= 的完整协议、域 和路径 (但不是文件名) ] URL 有子域 以及 那些 没有 子域?
https?:\/\/(?:[^\/ ]*\/)*
演示 here.
说明
http //Should start with http
s? // s is optional
:\/\/ // should follow up with ://
(?: //START Non capturing group
[^\/ ]* //Any character but a / or a space
\/ //Ends with /
) //END Non capturing group
* //Repeat non-capturing group