Skip to main content
 首页 » 编程设计

c#之为什么 visual studio 中的正则表达式在程序中不起作用

2024年01月29日30hnrainll

我可以在 visual studio 中使用正则表达式搜索进行匹配。

(/:d.*.csv) 匹配“/content/equities/scripvol/datafiles/06-10-2009-TO-”中的“/06-10-2009-TO-05-10-2011SBINALLN.csv” 05-10-2011SBINALLN.csv"

但是,同一个 RegEx 无法以编程方式工作,如下所示:

    static private string GetFileName(string url) 
    { 
        // (/:d.*\.csv)  this RegEx works in visual studio! 
        Match match = Regex.Match(url, @"(/:d.*\.csv)"); 
        string key = null; 
        // Here we check the Match instance. 
        if (match.Success) 
        { 
            // Finally, we get the Group value and display it. 
            key = match.Groups[1].Value; 
        } 
        return key; 
    } 

请您参考如下方法:

您的代码运行良好 - RegEx 与您认为的不匹配。看来您正在尝试获取路径的最后一部分。如果是这样,请使用以下代码:

static private string GetFileName(string url) 
{ 
    Match match = Regex.Match(url, @"/[^/]*$"); 
    string key = null; 
 
    if (match.Success) 
    { 
        key = match.Value; 
    } 
 
    return key; //Returns "/06-10-2009-TO-05-10-2011SBINALLN.csv" 
} 

备选

您也可以使用 System.IO.Path.GetFileName(url)。

static private string GetFileName(string url) 
{ 
    // Returns "06-10-2009-TO-05-10-2011SBINALLN.csv" (removes backslash) 
    return System.IO.Path.GetFileName(url);  
}