It would be nice if something like /(.*[^\/])\/*(\?.*)?/
worked. But the problem is that the regex engine will find the best possible match for (.*[^\/])\/*
, even if this means matching (\?.*)?
against the empty string.*
You could do the following:
/(.*[^\/])\/*(\?.*)|(.*[^\/])/
This is slightly unsatisfactory in that you get 3 capture groups even though you only wanted 2. So you could do this instead, if (the version of) the language you're using allows the (?|...)
construct:
/(?|(.*[^\/])\/*(\?.*)|(.*[^\/]))/
*More generally, suppose the regex engine is faced with a regex /AB/
. The match it returns will contain the best possible match for /A/
(by which I mean the best match that can actually be extended to a match for /AB/
). To put it another way, it doesn't backtrack into A
until it's finished searching for matches for B
.