简体   繁体   English

正则表达式将特定路径与特定查询参数匹配

[英]Regex to match specific path with specific query param

I'm struggling with creating regex to match URL path with query param that could be in any place. 我正在努力创建正则表达式以匹配URL路径与可能在任何地方的查询参数。

For example URLs could be: 例如,URL可以是:

/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

where I need to target param target specifically on /page 我需要在/page专门针对param target

This regex works only to find the param \\A?target=[^&]+&* . 这个正则表达式只能找到参数\\A?target=[^&]+&*

Thanks! 谢谢!

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. 一般规则是,如果要解析params,请使用URL解析器,而不是自定义正则表达式。

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'

And then check those values in ifs: 然后在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' {
  # ...
}

See also: 也可以看看:

EDIT 编辑

If you have to use regex try this one: 如果你必须使用正则表达式试试这个:

\/page(?=\?).*[?&]target=[^&\s]*(&|$)

Demo 演示

Explanation: 说明:

  • \\/page(?=\\?) - matches path (starts with / then page then lookahead for ? ) \\/page(?=\\?) - 匹配路径(以/然后page开头,然后查找?
  • .*[?&]target=[^&\\s]*($|&) matches param name target : .*[?&]target=[^&\\s]*($|&)匹配param name target
    • located anywhere (preceded by anything .* ) 位于任何地方(前面有任何东西.*
    • [?&] preceded with ? [?&]之前是? or & &
    • followed by its value (=[^&\\s]*) 后跟其值(= [^&\\ s] *)
    • ending with end of params ( $ ) or another param ( & ) 以params( $ )或另一个param( & )结束

If you're looking for a regex then you may use: 如果您正在寻找正则表达式,那么您可以使用:

/\/page\?(?:.*&)?target=[^&]*/i

RegEx Demo RegEx演示

RegEx Details: RegEx详细信息:

  • \\/page\\? : Match text /page? :匹配文字/page? :
  • (?:.*&)? : Match optional text of any length followed by & :匹配任意长度的可选文本,后跟&
  • target=[^&]* : Match text target= followed by 0 or more characters that are not & target=[^&]* :匹配文本target=后跟0个或更多不是&字符

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM