I have a regular expression that works fine for me when used in ASP.NET Page Routing for URL rewriting.
However, when I try and use it elsewhere in my ASP.NET code it lets past strings that I do not want it to.
My regular expression is,
[-_a-zA-Z0-9/]+(\.aspx(\?.+)?)?
which is meant to allow strings with files/paths with no extension or with a .aspx file extension, but disallow files/paths with other extensions, eg. “whatever.js”.
I am using it unsuccessfully elsewhere in my application like this…
if (Regex.IsMatch(pageUrl, @"[-_a-zA-Z0-9/]+(\.aspx(\?.+)?)?"))
It seems that as part of the string matches it lets it through. But how can I make sure the entire string (pageUrl) matches?
Use ^ and $ at the start and end to force it to make the whole string:
See the MSDN page on “Anchors in regular expressions” for more details.