Extract numbers if matched string format

I want to check if the input line should follow the pattern, and if it extracts information from it.

My model is like this one Episode 000 (Season 00). 00s are numbers that can range from 0 to 9. Now I want to check if this input matches Episode 094 (Season 02)this pattern, and therefore it needs to extract these two numbers, so I get two integer variables 94and 2:

string latestFile = "Episode 094 (Season 02)";
if (!Regex.IsMatch(latestFile, @"^(Episode)\s[0-9][0-9][0-9]\s\((Season)\s[0-9][0-9]\)$"))
    return

int Episode = Int32.Parse(Regex.Match(latestFile, @"\d+").Value);
int Season = Int32.Parse(Regex.Match(latestFile, @"\d+").Value);

The first part, where I check to see if the common string works with the template, but I think it can be improved. In the second part, where I actually extract the numbers that I am stuck with and what I wrote above obviously does not work, because it captures all the digits from the string. Therefore, if any of you can help me figure out how to extract only three characters after Episodeand two characters after, Seasonthat would be great.

+4
source share
2 answers
^Episode (\d{1,3}) \(Season (\d{1,2})\)$

It captures 2 numbers (even with lengths from 1 to 3/2) and returns them as a group. You can go even further and name your groups:

^Episode (?<episode>\d{1,3}) \(Season (?<season>\d{1,2})\)$

and then call them.

An example of using groups:

string pattern = @"abc(?<firstGroup>\d{1,3})abc";
string input = "abc234abc";
Regex rgx = new Regex(pattern);
Match match = rgx.Match(input);
string result = match.Groups["firstGroup"].Value; //=> 234

You can see what the expressions mean and test them here

+3
source

^(Episode)\s[0-9][0-9][0-9]\s\((Season)\s[0-9][0-9]\)$ Episode Season , , , - . :

^Episode\s([0-9][0-9][0-9])\s\(Season\s([0-9][0-9])\)$

3- [0-9][0-9][0-9] \d{3} [0-9][0-9] \d{2}.

^Episode\s(\d{3})\s\(Season\s(\d{2})\)$

, \d+.

\s ^Episode (\d{3}) \(Season (\d{2})\)$

string latestFile = "Episode 094 (Season 02)";
GroupCollection groups = Regex.Match(latestFile, @"^Episode (\d{3}) \(Season (\d{2})\)$").Groups;
int Episode = Int32.Parse(groups[1].Value);
int Season = Int32.Parse(groups[2].Value);
Console.WriteLine(Episode);
Console.WriteLine(Season);

:

94
2

#

+2

Source: https://habr.com/ru/post/1694976/


All Articles