Question

I'm trying to match my application uri to a set of routes, and for the default route I thought about allowing bb.com/home or bb.com/ (empty) to be the allowed options on the first uri segment, and the same for the second. I'm not sure the way I am checking for empty values is the best :

#^/?(?P<controller>([.*]{0}|home))(?:/(?P<action>([.*]{0}|test)))?/?$#uD

Notice the [.*]{0}

Is there a better way to do it?

Was it helpful?

Solution

You could make it lazy: .*?, that should match nothing every time.


Also, you don't have to have so many capture groups. You even have a numbered capture group within a named capture group. This is how I would write the expression:

^/?(?P<controller>.*?|home)/(?P<action>.*?|test)/?$

This retains the two named capture groups, but gets rid of the nested numbered capture group and also the non-capturing group which was not necessary.

OTHER TIPS

By placing .* inside a character class [] you're asking to match a literal dot . and literal * instead of the dot being able to match any character (except newline) and * being able to act as a quantifier.

By using the {0} range quantifier, this matches exactly 0 times (token is being ignored). You're not going to get the results you expect and their is no need to do this either.

You could simply add the ? for a non-greedy match and remove the excess capturing groups here.

~^/?(?P<controller>.*?|home)/(?P<action>.*?|test)/?$~i

However think about how this may work, you said you wanted to allow bb.com/home, well this will also match patterns that you possibly do not want.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top