John
John

Reputation: 139

ASP.NET Regex Issue

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?

Upvotes: 2

Views: 528

Answers (2)

Mahesh KP
Mahesh KP

Reputation: 6446

try like this

System.Text.RegularExpressions.Regex regexUrl = new System.Text.RegularExpressions.Regex(" [-_a-zA-Z0-9/]+(.aspx(\?.+)?)?");

check regexUrl.IsMatch(pageUrl)

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500275

Use ^ and $ at the start and end to force it to make the whole string:

if (Regex.IsMatch(pageUrl, @"^[-_a-zA-Z0-9/]+(.aspx(\?.+)?)?$"))

See the MSDN page on "Anchors in regular expressions" for more details.

Upvotes: 5

Related Questions