【问题标题】:Extracting year from a string从字符串中提取年份
【发布时间】:2013-07-18 15:58:17
【问题描述】:

我的字符串格式为:

AM Kaplan, M Haenlein - Business horizons, 2010 - Elsevier
A Lenhart, K Purcell, A Smith, K Zickuhr - 2010 - pewinternet.org

并且想提取年份。

我正在使用:

year = year.Substring(year.LastIndexOf(",") + 1, year.LastIndexOf("-") - 1).Trim();

但是会出现长度错误,并且当需要的最后一个索引是“-”作为子字符串的开头而不是“,”时,这也会中断。

如何正确提取年份?

【问题讨论】:

  • 首先,Substring 采用起始索引和长度,而不是起始索引和结束索引。其次,您需要在此处明确定义您的参数。您的示例不适用于第二个字符串。还有其他可能的排列方式吗?
  • 想到正则表达式。
  • 还有其他的,但这是发生的两种排列。

标签: c# string substring


【解决方案1】:

以下表达式验证 authors - optionalPublisher year - site 格式的字符串:

var s = "AM Kaplan, M Haenlein - Business horizons, 2010 - Elsevier";

var match = Regex.Match(s, @".+ - .*(\d{4}) - .+");
if (match.Success)
{
     var year = match.Groups[1].Value;
}

【讨论】:

  • 这里最安全的解决方案。假设 4 位数字不会随意出现在作者列表中可能是公平的。
【解决方案2】:
s = 'A Lenhart, K Purcell, A Smith, K Zickuhr - 2010 - pewinternet.org'

如果年份总是在用逗号分隔的字符串的最后一个元素中,并且总是在两个连字符之间,那么你可以做一些简单的事情,比如

last = s.split(',')[-1]
year = int(last.split(' - ')[1])

s.split(delimiter) 将字符串转换为list 对象,其中列表中的每个元素都是s 的子字符串,由delimiter 分区,在您的情况下是逗号和连字符。

【讨论】:

    【解决方案3】:

    看起来年份显示为逗号分隔字符串的最后一个元素,但它并不总是介于 2 个连字符之间。它看起来像它出现在最后一个连字符之前。如果总是这样,这行得通:

        int ExtractYear(string delimitedString)
        {
            // Only works if Year appears in the last split field of the delimitedString
            // and also Year is the 2nd to last sub-field of that last field.
            var fields = delimitedString.Split(new char[] {','});
            var subfields = fields.Last().Split(new char[] {'-'});
            int result = 0; 
            // -1 denotes bad value
            return int.TryParse(subfields[subfields.Length - 2], out result) ? result : -1;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-14
      • 1970-01-01
      • 2021-05-10
      • 2016-06-13
      • 2020-09-18
      • 1970-01-01
      • 2021-05-06
      • 1970-01-01
      相关资源
      最近更新 更多