Regular expression to match a string (1+ characters) that does NOT end in .ext (extension)

I need to test a url that it does not end with .asp

So test, test.html and test.aspx should match, but test.asp should not match.

Normally you'd test if the url does end with .asp and negate the fact that it matched using the NOT operator in code:

if(!regex.IsMatch(url)) { // Do something }

In that case the regular expression would be \.asp$ but in this case I need the regular expression to result in a match.


Background: I need to use the regular expression as a route contraint in the ASP.NET MVC RouteCollection.MapRoute extension method. The route needs to match all controllers but it should fall through when the controller in the url ends with .asp

Answers


The trick is to use negative lookbehind.

If you need just a yes/no answer:

(?<!\.asp)$

If you need to match the whole URL:

^.*(?<!\.asp)$

These regexes will work with any URL where the file name occurs at the end of the URL (i.e. URLs without a query or fragment). I'm assuming your URLs fit this limitation given the regex .asp$ in your question. If you want it to work with all URLs, try this:

^[^#?]+(?<!\.asp)([#?]|$)

Or this if you want the regex to match the whole URL:

^[^#?]+(?<!\.asp)([#?].+|$)

Not a regexp, but c# String.EndsWith method which could easily do the job.

ie

string test1 = "me.asp" ;
string test2 = "me.aspx" ;

test1.EndsWith(".asp") // true;
test2.EndsWith(".asp") // false ;

Try this

^((?!\.asp$).)*$

Need Your Help

Find regular expression string and replace it in R

regex r grep gsub

The purpose is to tidy a dataset by cleaning all variable names replications.

Is there an updated guide to the eu_ldap extension for the typo 3?

content-management-system typo3 openldap intraweb

I am trying to simulate an intranet CMS and installed the eu_ldap extension for typo3. Unfortunately the downloaded guide is out of date, and the current manual is of very little use to a typo 3 be...