2011-10-05 3 views
1

私はビジュアルスタジオで正規表現検索を使ってマッチを得ることができます。Visual Studioの正規表現がプログラムで動作しないのはなぜですか?

(/:d.*.csv)は、 "/ content/equity/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 Regexの正規表現と同じではありません。 –

+0

@msarchet正規表現 – Martin

答えて

1

と思われます。dは、Visual Studioの正規表現検索では動作しますが、ないRegex.Matchで、I以下のコードを試してみました。 dの代わりに[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

あなただけのファイル名の最後の部分をしたい場合は、これを使用する:

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

@MKVを使用したビジュアルスタジオ検索(ctrl + F)。それはうまく動作し、 '/' –

+1

@MKVを削除するだけです。私はこれについて最初に疑問を抱いていましたが、投稿する前にLINQPadでテストしました。それはうまく動作します。これは 'Path'が' schema:// path/to/resource'の形式のものを含め、UNCパスの任意の形式を処理するためです。 – Polynomial

+0

@Polynomial、+1! LINQPadが大好きです:) –

関連する問題