Friday, 23 August 2013

How to only allow certain number of forward slashes using regular expression?

How to only allow certain number of forward slashes using regular expression?

I'm routing my application and I'd like to only allow a maximum of 2
directory subpaths following a directory path of tags/. Hyphens and alnums
are the only allowable characters.
The following will all validate and be returned to the router as a single
match:
tags/how-to-bake
tags/how-to-bake/cookies
If there are more than 2 subpaths (or 2+ slashes, in other words) the
router should return no match.
My server redirects on trailing slashes (to the non-trailing slash URL) so
they don't need to be taken into consideration.
I'm currently using tags/([\w+\-\/]+)$ but this will allow infinitely many
subpaths, and I am forced to check the subpath length (forward slash
count) after the router returns a match.
I'm not sure how I can allow only 0 or 1 forward slashes in the character
set I wrote, while having word characters possibly follow, and then have
them all returned as a single match.
Is this possible with a regular expression?

No comments:

Post a Comment