2011-10-05 30 views
1

我能够在Visual Studio中使用正则表达式搜索获得匹配。为什么Visual Studio中的正则表达式不能在程序中工作?

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

但是,如下图所示相同的正则表达式不编程工作:

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

什么意思是在Visual Studio中工作 – msarchet

+2

Visual Studio的搜索正则表达式与.Net正则表达式不同。 –

+0

@msarchet使用正则表达式的视觉工作室搜索(ctrl + F) – Martin

回答

1

看来,尝试下面的代码,它的工作。用[0-9]代替:d。如Joel Rondeau所述,Visual Studio RegEx似乎与.NET RegEx不同。

static private string GetFileName(string url) 
    { 
     // (/:d[^"]*\.csv) this RegEx works in visual studio! 
     Match match = Regex.Match(url, @"(/[0-9].*\.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; 
     } 
     key = key.Replace("/", ""); 
     return key; 
    } 
3

你的代码的工作就好了 - 正则表达式只是不匹配像你认为它是。看起来你正在尝试获取路径的最后部分。如果是这样,使用下面的代码:

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

如果你只是想在文件名的最后一部分,使用:当我在Visual Studio中的正则表达式搜索d的作品,但不是在Regex.Match:

System.IO.Path.GetFileName("/content/equities/scripvol/datafiles/06-10-2009-TO-05-10-2011SBINALLN.csv"); 
+0

@MKV,不正确。它的工作原理,它只是删除'/' –

+1

@MKV - 我首先想到这个,但在发布之前在LINQPad中进行了测试。它工作正常。这是因为'Path'处理任何形式的UNC路径,包括'schema:// path/to/resource'形式的东西。 – Polynomial

+0

@Polynomial,+1!得爱LINQPad :) –

相关问题