tsvallender
tsvallender

Reputation: 2974

Problem creating regex to match filename

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!

Upvotes: 1

Views: 765

Answers (4)

Daniel Br&#252;ckner
Daniel Br&#252;ckner

Reputation: 59645

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

Upvotes: 0

Rob Fonseca-Ensor
Rob Fonseca-Ensor

Reputation: 15621

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"

Upvotes: 1

Grzenio
Grzenio

Reputation: 36649

Maybe try:

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

Upvotes: 0

Walt W
Walt W

Reputation: 3349

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.

Upvotes: 2

Related Questions