Question

I'm trying to match any requests for a url that do not have a folder character (/) or end with an extension (.aspx). I can ignore querystring values and fragments in the regular expression for now. So far I have the following.

^([\w-/]+)(?!\.aspx|/)$

However, if I run this expression it selected the final / in the group which I don't want it to do. The goal is to append .aspx to urls that do not have it specified using Isapi ReWrite and then forward the request onto the .NET engine.

the example below shows all characters in a current match in bold

asd.aspx
this
something.aspx
this/test/ (dont want the final /)
this-test/ (dont want the final /)
this-test
this-test/that/test

Can anyone suggest an expression that would not select the final / if found in the expression?

Was it helpful?

Solution

Try a look-behind assertion:

^([\w-/]+)(?<!/|\.aspx)$

OTHER TIPS

Move the / outside the group ():

^([\w-/]+)(?!\.aspx)/?$

Your first sentence doesn't match your regular expression or examples.
It seems to me that you want:

  1. If the string ends with .aspx don't process further.
  2. Otherwise if the string ends with / remove that slash.
  3. Process the string.

Maybe you're trying to do too much with a regular expression?

Why not explicitly test for your extension (.aspx), and if you don't have that then detect a terminal slash and remove it, before extra processing of the string?

That is to say: I'm sure it's possible to create a regular expression, with negative lookahead, that will do 1 & 2, but wouldn't it be clearer to do it explicitly.

You might also want to test some more examples:

foo/bar/.aspx
foo/bar.aspx/
foo.aspx/bar
foo.aspx/bar/

Just to be sure you know what you're expecting as output.

Remove the / from the regex and add it outside and specify that it can have 0 or 1 occurrence.

^([\w-/]+)(?!.aspx)(/){0,1}$

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