正则表达式将特定路径与特定查询参数匹配 [英] Regex to match specific path with specific query param
问题描述
我正在努力创建正则表达式以将 URL 路径与可能在任何地方的查询参数相匹配.
I'm struggling with creating regex to match URL path with query param that could be in any place.
例如网址可以是:
/page?foo=bar&target=1&test=1 <- should match
/page?target=1&test=2 <- should match
/page/nested?foo=bar&target=1&test=1 <- should NOT match
/page/nested?target=1&test=2 <- should NOT match
/another-page?foo=bar&target=1&test=1 <- should NOT match
/another-page?target=1&test=2 <- should NOT match
我需要在 /page
此正则表达式仅用于查找参数 \A?target=[^&]+&*
.
This regex works only to find the param \A?target=[^&]+&*
.
谢谢!
更新:需要第三方工具来决定在哪个页面上运行实验.它只接受在他们的仪表板上设置的规则表达式,所以我不能使用像 URL 解析器这样的代码工具.
UPDATE: It is needed for a third-party tool that will decide on which page to run an experiment. It only accepts setup on their dashboard with regular experssion so I cannot use code tools like URL parser.
推荐答案
一般规则是,如果您想解析参数,请使用 URL 解析器,而不是自定义正则表达式.
General rule is that if you want to parse params, use URL parser, not a custom regex.
在这种情况下,您可以使用例如:
In this case you can use for instance:
# http://a.b/ is just added to make URL parsing work
url = new URL("http://a.b/page?foo=bar&target=1&test=1")
url.searchParams.get("target")
# => 1
url.pathname
# => '/page'
然后在 ifs 中检查这些值:
And then check those values in ifs:
url = new URL("http://a.b/page?foo=bar&target=1&test=1")
url = new URL("http://a.b/page?foo=bar&target=1&test=1")
if (url.searchParams.get("foo") && url.pathname == '/page' {
# ...
}
另见:
- https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
- https://developer.mozilla.org/en-US/docs/Web/API/URL
编辑
如果你必须使用正则表达式,试试这个:
If you have to use regex try this one:
\/page(?=\?).*[?&]target=[^&\s]*(&|$)
说明:
\/page(?=\?)
- 匹配路径(以/
开头,然后是page
然后向前查找?代码>)
.*[?&]target=[^&\s]*($|&)
匹配参数名称target
:- 位于任何地方(以任何
.*
开头) [?&]
前有?
或&
- 后跟它的值 (=[^&\s]*)
- 以参数结尾 (
$
) 或另一个参数 (&
) 结束
\/page(?=\?)
- matches path (starts with/
thenpage
then lookahead for?
).*[?&]target=[^&\s]*($|&)
matches param nametarget
:- located anywhere (preceded by anything
.*
) [?&]
preceded with?
or&
- followed by its value (=[^&\s]*)
- ending with end of params (
$
) or another param (&
)
这篇关于正则表达式将特定路径与特定查询参数匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- located anywhere (preceded by anything
- 位于任何地方(以任何