pillarjs / path-to-regexp

Turn a path string such as `/user/:name` into a regular expression
MIT License
8.12k stars 381 forks source link

Non greedy repeats seem currently impossible #313

Closed Tofandel closed 1 month ago

Tofandel commented 1 month ago

I'm looking to get a route of the following format /:category(.*?)*/:pagePrefix('page')?/:page(\d+)?

But currently category will match anything even if I made the pattern inside non greedy, because the catch all of path-to-regexp is greedy and matches the rest

(So /category/sofa/page/1 results in category => [ 'sofa', 'page', '1'] and the rest is empty )

I'm looking for a solution to have the page prefix required only when the page parameter is provided, but did not find a more elegant way to do this because it seems /:category(.*?)*/(page/:page(\d+))? is not a supported syntax, /:category(.*?)*/(page/:page(\d+))? in theory works (if not for the greedy issue) but requires some postprocessing

The problem is that we cannot use just /:category(.*?)/(page/:page(\d+))? either, because then when we compile the route with a category like sofa/armchair then the slash gets url encoded which is not desired behavior

Can't we just make the catch all non greedy (As I see no reason not to and because we currently can't use anything after a catchall, wouldn't be a breaking change) or add a modifier like ? to it to allow non greedy like regex does?

blakeembrey commented 1 month ago

Did you intend to close this? I can't really understand the issue as written, since it's making a bunch of assumptions about this library that appear to be incorrect. Which version are you using? You can't mix and match regex and parameters like implied above. Also I don't think you'd ever want .*? for a parameter, based on your example just /:category would work. Why don't you just do ["/:category", "/:category/page/:page(\\d+)"]?

Tofandel commented 1 month ago

Yes sorry, this was meant for vue-router, I know they used this library in the past but in 4.x they made their custom implementation