In the example below, I want to get the string "2023". All the code I wrote for this is below. I think it shouldn't be hard to get the string "2023" like this. What is the simplest way to get the "2023" in the given string?
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);
CodePudding user response:
Try regular expressions:
var pattern = @"\b(\d\d\d\d)\b";
foreach (var match in Regex.Matches(raw, pattern))
{
// do something with match
}
CodePudding user response:
If you want to match 4 digits greater than 2000, you can use:
\b[2-9][0-9]{3}\b(?<!2000)
In parts, the pattern matches:
\b
A word boundary to prevent a partial match[2-9]
Match a digit 2-9[0-9]{3}
Match 3 digits 0-9\b
A word boundary(?<!2000)
Negative lookbehind, assert not 2000 directly to the left
Note that in C# using \d
also matches digits in other languages.