我需要一個正則表達式來讓C#返回匹配允許的路徑和文件名。需要路徑和文件擴展名匹配的正則表達式
以下應匹配:
a
(至少一個字符)xxx/bbb.aspx
(允許的路徑和僅.aspx擴展是允許的)bbb.aspx?aaa=1
(查詢字符串是允許的)
它不應該匹配:
aaa.
aaa.gif
(僅.aspx擴展允許)aaa.anythingelse
我需要一個正則表達式來讓C#返回匹配允許的路徑和文件名。需要路徑和文件擴展名匹配的正則表達式
以下應匹配:
a
(至少一個字符)xxx/bbb.aspx
(允許的路徑和僅.aspx擴展是允許的)bbb.aspx?aaa=1
(查詢字符串是允許的)它不應該匹配:
aaa.
aaa.gif
(僅.aspx擴展允許)aaa.anythingelse
.NET具有內置的功能與文件路徑的工作,包括調查文件擴展名。所以我強烈建議使用它們而不是正則表達式。以下是使用System.IO.Path.GetExtension()的可能解決方案。這是未經測試,但它應該工作。
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));
}
謝謝,但我需要它的URL重寫系統已經到位,所以不能使用這個抱歉。 – John 2011-04-05 01:13:56
C#使用PCRE嗎? – alex 2011-04-05 00:50:34
@alex:不。它有自己的語法(但非常相似,功能也很強大)。 – ridgerunner 2011-04-05 00:57:34