0

我得到了一些标题,我想查找本文中是否存在年份(1950-2050),但如果存在 2,我想查找第二年。我已经创建了一个方法。如果没有找到方法,我想返回 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;
    }
}

我的方法返回

2000 0 2000 2012

代替

2000 0 2012 2012

4

1 回答 1

2

您可以使用以下方法获取“第二个元素(如果存在),否则为第一个” 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;
}
于 2012-12-23T15:03:33.233 回答