tags:

views:

88

answers:

4

I am trying to create a regex in C# to extract the artist, track number and song title from a filename named like: 01.artist - title.mp3

Right now I can't get the thing to work, and am having problems finding much relevant help online.

Here is what I have so far:

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

I'm not getting any matches at all, and all help is appreciated!

+2  A: 

You might want to put ?'s before the <> tags in all your groupings, and put a + sign after your [a-z]'s, like so:

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

Then it should work. The ?'s are required so that the contents of the angled brackets <> are interpreted as a grouping name, and the +'s are required to match 1 or more repetitions of the last element, which is any character between (and including) a-z here.

Walt W
A: 

Maybe try:

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

Your artist and title groups are matching exactly one character. Try:

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

I really recommend http://www.ultrapico.com/Expresso.htm for building regular expressions. It's brilliant and free.

P.S. i like to type my regex string literals like so:

@"(?<trackNo>\d{1,3})\.(?<artist>[a-z]+\s-\s(?<title>[a-z]+)\.mp3"
Rob Fonseca-Ensor
+1 for the Expresso link
TLiebe
A: 

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

OUTPUT

01
Pink Floyd
Another Brick in the Wall
Daniel Brückner