gpt4 book ai didi

c# - 不同年份格式的正则表达式 c#

转载 作者:太空宇宙 更新时间:2023-11-03 12:10:18 27 4
gpt4 key购买 nike

所以我可以在字符串中包含 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 中,“年”组被解析为 int 并递增 1

Demo

关于c# - 不同年份格式的正则表达式 c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52651417/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com