2009-09-01 29 views
1

我試圖創建在C#中的正則表達式來提取一個文件名藝術家,曲目編號和歌曲名稱命名,如:01.artist - 現在title.mp3問題產生的正則表達式匹配文件名

我可以」不要讓事情發揮作用,並且在網上尋找相關的幫助時遇到問題。

這是我到目前爲止有:

string fileRegex = "(?<trackNo>\\d{1,3})\\.(<artist>[a-z])\\s-\\s(<title>[a-z])\\.mp3"; 
Regex r = new Regex(fileRegex); 
Match m = r.Match(song.Name); // song.Name is the filname 
if (m.Success) 
{ 
    Console.WriteLine("Artist is {0}", m.Groups["artist"]); 
} 
else 
{ 
    Console.WriteLine("no match"); 
} 

我沒有得到任何比賽都和所有幫助表示讚賞!

回答

2

你可能想要把的在所有分組的<>標記之前,並把後您的[A-Z] +號的,就像這樣:

string fileRegex = "(?<trackNo>\\d{1,3})\\.(?<artist>[a-z]+)\\s-\\s(?<title>[a-z]+)\\.mp3"; 

那麼它應該工作。這些符號是必需的,以便角度括號<>的內容被解釋爲分組名稱,並且+必須匹配最後一個元素的一個或多個重複,最後一個元素是(和包括)在這裏。

0

也許嘗試:

"(?<trackNo>\\d{1,3})\\.(<artist>[a-z]*)\\s-\\s(<title>[a-z]*)\\.mp3"; 
1

您的藝術家和標題組匹配一個字符。嘗試:

"(?<trackNo>\\d{1,3})\\.(?<artist>[a-z]+\\s-\\s(?<title>[a-z]+)\\.mp3" 

我真的建議http://www.ultrapico.com/Expresso.htm建設正則表達式。這是輝煌而自由的。

P.S.我喜歡打字我正則表達式的字符串文字像這樣:

@"(?<trackNo>\d{1,3})\.(?<artist>[a-z]+\s-\s(?<title>[a-z]+)\.mp3" 
+0

+1爲快報鏈接 – TLiebe 2009-09-01 15:53:11

0

CODE

String fileName = @"01. Pink Floyd - Another Brick in the Wall.mp3"; 
String regex = @"^(?<TrackNumber>[0-9]{1,3})\. ?(?<Artist>(.(?!= -))+) - (?<Title>.+)\.mp3$"; 

Match match = Regex.Match(fileName, regex); 

if (match.Success) 
{ 
    Console.WriteLine(match.Groups["TrackNumber"]); 
    Console.WriteLine(match.Groups["Artist"]); 
    Console.WriteLine(match.Groups["Title"]); 
} 

輸出

 
01 
Pink Floyd 
Another Brick in the Wall