John
John

Reputation: 139

Need Regular Expression for path and file extension matching

I need a regular expression for C# to return a match for allowed paths and file names.

The following should match:

It should not match for:

Upvotes: 1

Views: 1477

Answers (2)

jb.
jb.

Reputation: 10361

.NET has built-in features for working with file paths, including finding file extensions. So I would strongly suggest using them instead of a regex. Here is a possible solution using System.IO.Path.GetExtension(). This is untested but it should work.

private static bool IsValid(string strFilePath)
{
    //to deal with query strings such as bbb.aspx?aaa=1
    if(strFilePath.Contains('?'))
        strFilePath = strFilePath.Substring(0, strFilePath.IndexOf('?'));

    //the list of valid extensions
    string[] astrValidExtensions = { ".aspx", ".asp" };

    //returns true if the extension of the file path is found in the 
    //list of valid extensions
    return astrValidExtensions.Contains(
        System.IO.Path.GetExtension(strFilePath));
}

Upvotes: 0

Czechnology
Czechnology

Reputation: 15012

Try this:

[\w/]+(\.aspx(\?.+)?)?

Upvotes: 1

Related Questions