I need a regular expression for C# to return a match for allowed paths and file names.
The following should match:
a
(at least one character) xxx/bbb.aspx
(path allowed and only .aspx extension is allowed) bbb.aspx?aaa=1
(querystring is allowed) It should not match for:
aaa.
aaa.gif
(only .aspx extension allowed) aaa.anythingelse
尝试这个:
[\w/]+(\.aspx(\?.+)?)?
.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));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.