需要正则表达式进行路径和文件扩展名匹配

本文关键字:文件 扩展名 路径 正则表达式 | 更新日期: 2023-09-27 17:48:54

我需要 C# 的正则表达式来返回允许的路径和文件名的匹配项。

以下内容应匹配:

  • a(至少一个字符)
  • xxx/bbb.aspx(允许路径,仅允许.aspx扩展名)
  • bbb.aspx?aaa=1(允许查询字符串)

它不应匹配:

  • aaa.
  • aaa.gif(仅允许.aspx扩展)
  • aaa.anythingelse

需要正则表达式进行路径和文件扩展名匹配

试试这个:

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

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));
}