问题
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/
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 (&
)
- located anywhere (preceded by anything
回答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 texttarget=
followed by 0 or more characters that are not&
来源:https://stackoverflow.com/questions/57419840/regex-to-match-specific-path-with-specific-query-param