[英]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,直接向左断言不是2000Note that in C# using \d
also matches digits in other languages .请注意,在 C# 中使用\d
也可以匹配其他语言中的数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.