简体   繁体   中英

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.

For example URLs could be:

/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

This regex works only to find the param \\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.

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'

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' {
  # ...
}

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 ? )
  • .*[?&]target=[^&\\s]*($|&) matches param name target :
    • located anywhere (preceded by anything .* )
    • [?&] preceded with ? or &
    • followed by its value (=[^&\\s]*)
    • ending with end of params ( $ ) or another param ( & )

If you're looking for a regex then you may use:

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

RegEx Demo

RegEx Details:

  • \\/page\\? : Match text /page? :
  • (?:.*&)? : Match optional text of any length followed by &
  • target=[^&]* : Match text target= followed by 0 or more characters that are not &

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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