Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for matching season and episode

Tags:

c#

.net

regex

I'm making small app for myself, and I want to find strings which match to a pattern but I could not find the right regular expression.

Stargate.SG-1.S01E08.iNT.DVDRip.XviD-LOCK.avi

That is expamle of string I have and I only want to know if it contains substring of S[NUMBER]E[NUMBER] with each number max 2 digits long.

Can you give me a clue?

like image 861
bakua Avatar asked Aug 22 '12 22:08

bakua


2 Answers

Regex

Here is the regex using named groups:

S(?<season>\d{1,2})E(?<episode>\d{1,2})

Usage

Then, you can get named groups (season and episode) like this:

string sample = "Stargate.SG-1.S01E08.iNT.DVDRip.XviD-LOCK.avi";
Regex  regex  = new Regex(@"S(?<season>\d{1,2})E(?<episode>\d{1,2})");

Match match = regex.Match(sample);
if (match.Success)
{
    string season  = match.Groups["season"].Value;
    string episode = match.Groups["episode"].Value;
    Console.WriteLine("Season: " + season + ", Episode: " + episode);
}
else
{
    Console.WriteLine("No match!");
}

Explanation of the regex

S                // match 'S'
(                // start of a capture group
    ?<season>    // name of the capture group: season
    \d{1,2}      // match 1 to 2 digits
)                // end of the capture group
E                // match 'E'
(                // start of a capture group
    ?<episode>   // name of the capture group: episode
    \d{1,2}      // match 1 to 2 digits
)                // end of the capture group
like image 80
mmdemirbas Avatar answered Sep 19 '22 19:09

mmdemirbas


There's a great online test site here: http://gskinner.com/RegExr/

Using that, here's the regex you'd want:

S\d\dE\d\d

You can do lots of fancy tricks beyond that though!

like image 29
Ted Spence Avatar answered Sep 20 '22 19:09

Ted Spence