Reputation: 10981
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?
Upvotes: 1
Views: 134
Reputation: 70722
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.
Upvotes: 2
Reputation: 9591
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.
Upvotes: 2