Regex to match specific path with specific query param

主宰稳场 提交于 2020-02-03 11:07:07

问题


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.


回答1:


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:

  • https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
  • https://developer.mozilla.org/en-US/docs/Web/API/URL

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 (&)



回答2:


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 &


来源:https://stackoverflow.com/questions/57419840/regex-to-match-specific-path-with-specific-query-param

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!