简体   繁体   English

在字符串中获取年份的最简单方法是什么?

[英]What is the simplest way to get the year in a string?

In the example below, I want to get the string "2023".在下面的示例中,我想获取字符串“2023”。 All the code I wrote for this is below.我为此编写的所有代码都在下面。 I think it shouldn't be hard to get the string "2023" like this.我认为像这样得到字符串“2023”应该不难。 What is the simplest way to get the "2023" in the given string?在给定字符串中获取“2023”的最简单方法是什么?

const string raw = @"TAAD, Türkiye Adalet Akademisi'nin 95. Kuruluş Yıl Dönümü Armağanı, y.78, S.179, Temmuz 2023, s.108-157";
var frst = raw.Split(',').FirstOrDefault(x => x.Any(char.IsDigit) && Convert.ToInt32(new string(x.Where(char.IsDigit).Take(4).ToArray())) > 2000);
var scnd = new string(frst?.Where(char.IsDigit).Take(4).ToArray());
if (scnd.Length > 0 && Convert.ToInt32(scnd) > 2000) MessageBox.Show(scnd);

Try regular expressions:尝试正则表达式:

var pattern = @"\b(\d{4})\b";
foreach (var match in Regex.Matches(raw, pattern))
{
  // do something with match
}

If you want to match 4 digits greater than 2000, you can use:如果要匹配大于2000的4位数字,可以使用:

\b[2-9][0-9]{3}\b(?<!2000)

In parts, the pattern matches:在某些部分,模式匹配:

  • \b A word boundary to prevent a partial match \b防止部分匹配的单词边界
  • [2-9] Match a digit 2-9 [2-9]匹配数字 2-9
  • [0-9]{3} Match 3 digits 0-9 [0-9]{3}匹配 3 位数字 0-9
  • \b A word boundary \b单词边界
  • (?<!2000) Negative lookbehind, assert not 2000 directly to the left (?<!2000)负向lookbehind,直接向左断言不是2000

Regex demo正则表达式演示

Note that in C# using \d also matches digits in other languages .请注意,在 C# 中使用\d也可以匹配其他语言中的数字

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将字符串转换为流的最简单方法是什么? - What is the simplest way to convert a string to a stream? 给定一个字符串数组,对它们进行随机排序的最简单方法是什么? - Given an array of string what is the simplest way to sort them randomly? 从 XmlDocument 中获取带有换行符的缩进 XML 的最简单方法是什么? - What is the simplest way to get indented XML with line breaks from XmlDocument? 有没有办法得到一个字符串,直到一年的价值? - Is there a way to get a string up until a year value? 解析此表的最简单方法是什么: - What is the simplest way to parse this table: 应用主题的最简单方法是什么 - What is the simplest way to apply themeing 编码列表的最简单方法是什么<String>成纯字符串并将其解码回来? - What's the simplest way to encoding List<String> into plain String and decode it back? 计算一年第一周星期一的最简单方法是什么 - whats the simplest way to calculate the Monday in the first week of the year 做字符串包含使用Kendo Grid和Odata数据源对数字列进行过滤的最简单方法是什么? - What's the simplest way to do string contains filtering on a numeric column with a Kendo Grid and Odata data source? 区分Windows版本的最简单方法是什么? - What is the simplest way to differentiate between Windows versions?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM