NYTom
NYTom

Reputation: 524

Using Regular Expression how to remove if a certain character is at the end?

I am trying to write a URL rewriter rule in IIS7. My current reg expression is ^(policy|pricing|contact|gallery)/(.*) My Rewrite rule is: /{R:1}.aspx?cat={R:2}

policy/ (Keep Slash in this case, WORKS)

gallery/soccer (No slash provided so this WORKS)

gallery/soccer/ (needs to remove last slash)

gallery/soccer/girls/ (needs to remove last slash)

Any ideas would be great, I know how I would approach this in languages like .Net, but I need to strictly do this as a regular expression rule in IIS.

Upvotes: 2

Views: 163

Answers (3)

user557597
user557597

Reputation:

This might work

^(policy|pricing|contact|gallery)/([^/]*(?:/[^/]+)*)

Upvotes: 2

Andrew Clark
Andrew Clark

Reputation: 208565

I think the following should work:

^(policy|pricing|contact|gallery)/(.*?)/?$

The /? at the end means "match a / one or zero times", or in other words it is optional. Just adding this to the end wouldn't work because a / would still be consumed by the .*, so we need to change the .* to .*? so that it is no longer greedy.

The $ anchor is necessary so that the match doesn't end too early.

Note that the trailing / will still be a part of the match, but it will not be a part of the second capture group so your rewrite rule should work properly.

See it working: http://www.rubular.com/r/s8IqIlaqoz

Upvotes: 1

Jay
Jay

Reputation: 57959

I think that if you explicitly put it at the end (I have not escaped / because it looks like you're not doing so), you will effectively remove it in your re-write by not including that group.

^(policy|pricing|contact|gallery)/(.*)/?$

By adding $ we are ensuring that only a final forward slash is removed -- there can still be n forward slashes in between.

Upvotes: 0

Related Questions