c# - 从字符串中提取年份

标签 c# string substring

我的字符串格式为:

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();

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

如何正确提取年份?

最佳答案

以下表达式验证作者 - 可选出版商年份 - 网站 格式的字符串:

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;
}

关于c# - 从字符串中提取年份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17728453/

相关文章:

python - 如何在 python 中将字符串转换为源代码?

python - 如何在一行中找到一个子字符串并从该行追加到下一个子字符串?

javascript - 寻找从字符串中提取未知子字符串的最简单方法。 (术语用斜杠分隔)

c - 使用指针查找子字符串

c# - 自动大写Datagrid输入

c# - 在 C# 中序列化和反序列化自引用对象

c# - Windows 窗体文本框回车键

c# - 所以我从来没有完全理解使用 Private 的好处

Ruby 正则表达式字符串匹配 t =~/^\d{2}( :\d{2}){2}$/

java - 为什么我收到 "String index out of range: 53"错误?