Incognito
Incognito

Reputation: 455

Find the 2nd Year if exist with regular expressions

Im getting some titles and i want to find if there is year (1950-2050) in this text but i want to find the 2nd year if 2 exists. I have already created a method. If no method is found i want to return 0.

string text1 = "Name 2000";
string text2 = "Name";
string text3 = "2000 2012";
string text4 = "2012 Name";

public static int get_title_year(string title)
{
    string pattern = @"\b(?<Year1>\d{4})";
    Regex rx = new Regex(pattern);
    if (rx.IsMatch(title))
    {
        Match match = rx.Match(title);
        return Convert.ToInt16(match.Groups[1].Value);
    }
    else
    {
        return 0;
    }
}

My method returns

2000 0 2000 2012

Instead of

2000 0 2012 2012

Upvotes: 0

Views: 100

Answers (1)

Mark Byers
Mark Byers

Reputation: 838186

You can get "the second element if present, else the first" by using Take(2).LastOrDefault():

public static int get_title_year(string title)
{
    string pattern = @"\b\d{4}\b";
    Regex regex = new Regex(pattern);
    int year = regex.Matches(title)
                    .Cast<Match>()
                    .Select(m => int.Parse(m.Value))
                    .Take(2)
                    .LastOrDefault();
    return year;
}

Upvotes: 2

Related Questions