Simple IIS 7 regex with optional 1, 2 or 3 values

2019-07-01 13:45发布

问题:

I'm trying to make a regex match the following URL:

www.mydomain.com/newyear/food/maincourse/

and have it rewrite to default.aspx?occasion=(newyear)&type=(food)&category=(maincourse)

It works fine with:

([_0-9a-zA-Z]+)/([_0-9a-zA-Z-]+)/([_0-9a-zA-Z-]+)/$

but I would want it to work with just www.mydomain.com/newyear/food/ as well, and just rewrite with category empty. The only way I can do this now, is by n00bing, and creating 3 rewrite rules - one for each value.

I'm pretty sure there's a smarter way, and please let me know. :)

回答1:

Should be very simple, make the slashes and the last two tokens optional:

([_0-9a-zA-Z]+)/?([_0-9a-zA-Z-]*)/?([_0-9a-zA-Z-]*)/?$


回答2:

If you're looking for 'less than simple', you can do unicode checking since urls can now accept them (though you may not choose them for your own domain above).

([[:alpha:]]|[[:punct:]])+/?([[:alpha:]]|[[:punct:]])*/?([[:alpha:]]|[[:punct:]])*