不同年份格式的正则表达式 c#
Regex expression for different year formats c#
所以我可以在字符串中包含 1 年或更长时间,格式可以是 2 位数字即“18”、4 位数字即“2018”、完整日期字符串即“12/04/2018”,或者组合
在 C# 中使用正则表达式,我需要遍历此字符串以获取包含这些格式中任何一种的年份的所有值,并将其增加 1 年。
例如,这个字符串
"This is a string that has a 2 digit year - 15, a 4 digit year - 2015, and from date 01/01/2015 to date 02/03/2016"
应该变成
"This is a string that has a 2 digit year - 16, a 4 digit year - 2016, and from date 01/01/2016 to date 02/03/2017"
此代码的问题在于使用索引超出范围的日期。
我需要一个逻辑来处理这 3 个格式年,拜托。如果它包含独立有效年份 2 位数字、4 位数字或日期(格式 dd/mm/yyyy)是条件
public string Increment(string text)
{
if (text == null) return null;
var builder = new StringBuilder(text);
var matches = Regex.Matches(text, @"\b(?:\d{4}|\d{2})\b");
foreach (Match match in matches)
{
if (match.Success)
{
builder.Remove(match.Index, match.Length);
builder.Insert(match.Index, int.Parse(match.Value) + 1);
}
}
return builder.ToString();
}
您可以将 Regex.Replace 与 MatchEvaluator 一起使用。试试这个代码
var regex = new Regex("\b(?<prefix>\d{2}/\d{2}/)?(?<year>\d{2}|\d{4})\b");
var result = regex.Replace(text, match => $"{match.Groups["prefix"].Value}{int.Parse(match.Groups["year"].Value) + 1}");
正则表达式包含两组:可选前缀和年份。在 MatchEvaluator "year" 组中解析为 int 并递增 1
所以我可以在字符串中包含 1 年或更长时间,格式可以是 2 位数字即“18”、4 位数字即“2018”、完整日期字符串即“12/04/2018”,或者组合 在 C# 中使用正则表达式,我需要遍历此字符串以获取包含这些格式中任何一种的年份的所有值,并将其增加 1 年。
例如,这个字符串
"This is a string that has a 2 digit year - 15, a 4 digit year - 2015, and from date 01/01/2015 to date 02/03/2016"
应该变成
"This is a string that has a 2 digit year - 16, a 4 digit year - 2016, and from date 01/01/2016 to date 02/03/2017"
此代码的问题在于使用索引超出范围的日期。 我需要一个逻辑来处理这 3 个格式年,拜托。如果它包含独立有效年份 2 位数字、4 位数字或日期(格式 dd/mm/yyyy)是条件
public string Increment(string text)
{
if (text == null) return null;
var builder = new StringBuilder(text);
var matches = Regex.Matches(text, @"\b(?:\d{4}|\d{2})\b");
foreach (Match match in matches)
{
if (match.Success)
{
builder.Remove(match.Index, match.Length);
builder.Insert(match.Index, int.Parse(match.Value) + 1);
}
}
return builder.ToString();
}
您可以将 Regex.Replace 与 MatchEvaluator 一起使用。试试这个代码
var regex = new Regex("\b(?<prefix>\d{2}/\d{2}/)?(?<year>\d{2}|\d{4})\b");
var result = regex.Replace(text, match => $"{match.Groups["prefix"].Value}{int.Parse(match.Groups["year"].Value) + 1}");
正则表达式包含两组:可选前缀和年份。在 MatchEvaluator "year" 组中解析为 int 并递增 1