我如何正则表达式 url 的一部分
How do I regex part of url
我需要帮助解决正则表达式 (PCRE)。我想从下面的多个 url 中提取 hello-world
部分。到目前为止我得到了这个:
^/news/(.*?)/$
https://www.example.com/news/2017-08-09/hello-world/topics/
https://www.example.com/news/2017-08-09/hello-world/gallery/
https://www.example.com/news/2017-08-09/hello-world/
但这捕获了 2017-08-09/hello-world/topics
,我只需要 hello-world
如果 hello-world 代表一个未知的文本,其余的是固定的,试试这个:
^/news/2017-08-09/(.*?)/.*$
如果日期不固定,您可以指定它的格式并使用它来代替,例如 \d{4}-\d{2}-\d{2} 或您需要的任何格式。
您可以在 PCRE 中使用此正则表达式:
~/news/[^/]*/\K[^/]+~
/news/[^/]*/
:匹配 /news/
后跟零个或多个非 /
后跟 /
\K
: 放弃匹配信息
[^/]+
:匹配一个或多个非/
字符
您也可以使用捕获组:
/news/[^/]*/([^/]+)
并提取捕获组#2
[0-9]{4}-[0-9]{2}-[0-9]{2}/(.*?)/
第 1 组有 hello world
我需要帮助解决正则表达式 (PCRE)。我想从下面的多个 url 中提取 hello-world
部分。到目前为止我得到了这个:
^/news/(.*?)/$
https://www.example.com/news/2017-08-09/hello-world/topics/
https://www.example.com/news/2017-08-09/hello-world/gallery/
https://www.example.com/news/2017-08-09/hello-world/
但这捕获了 2017-08-09/hello-world/topics
,我只需要 hello-world
如果 hello-world 代表一个未知的文本,其余的是固定的,试试这个:
^/news/2017-08-09/(.*?)/.*$
如果日期不固定,您可以指定它的格式并使用它来代替,例如 \d{4}-\d{2}-\d{2} 或您需要的任何格式。
您可以在 PCRE 中使用此正则表达式:
~/news/[^/]*/\K[^/]+~
/news/[^/]*/
:匹配/news/
后跟零个或多个非/
后跟/
\K
: 放弃匹配信息[^/]+
:匹配一个或多个非/
字符
您也可以使用捕获组:
/news/[^/]*/([^/]+)
并提取捕获组#2
[0-9]{4}-[0-9]{2}-[0-9]{2}/(.*?)/ 第 1 组有 hello world