2011-04-05 134 views
1

我需要一個正則表達式來讓C#返回匹配允許的路徑和文件名。需要路徑和文件擴展名匹配的正則表達式

以下應匹配:

  • a(至少一個字符)
  • xxx/bbb.aspx(允許的路徑和僅.aspx擴展是允許的)
  • bbb.aspx?aaa=1(查詢字符串是允許的)

它不應該匹配:

  • aaa.
  • aaa.gif(僅.aspx擴展允許)
  • aaa.anythingelse
+0

C#使用PCRE嗎? – alex 2011-04-05 00:50:34

+0

@alex:不。它有自己的語法(但非常相似,功能也很強大)。 – ridgerunner 2011-04-05 00:57:34

回答

1

試試這個:

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

在regexpal.com上測試 - 適用於我 – 2011-04-05 00:59:06

+0

謝謝,這似乎很好! – John 2011-04-05 01:19:57

+0

必須稍微改變它以接受帶連字符的名稱:[-_a-zA-Z0-9 /] +(\。aspx(\?。+)?)? – John 2011-04-05 01:43:47

0

.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)); 
} 
+0

謝謝,但我需要它的URL重寫系統已經到位,所以不能使用這個抱歉。 – John 2011-04-05 01:13:56