簡體   English   中英

創建正則表達式以匹配文件名時出現問題

[英]Problem creating regex to match filename

我正在嘗試在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");
}

我根本沒有任何比賽,感謝所有幫助!

您可能希望在所有分組中的<>標記之前放置?,並在[az]的后面放置+號,如下所示:

string fileRegex = "(?<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構建正則表達式。 它是輝煌而免費的。

PS我喜歡這樣輸入我的正則表達式字符串文字:

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

也許嘗試:

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

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

OUTPUT

01
Pink Floyd
Another Brick in the Wall

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM