替换.NET RegEx Matches集合中的特定匹配项

时间:2015-06-28 22:23:52

标签: c# regex

我使用C#替换文本文件中的日期值。我逐行解析文件并尝试单独替换日期,因为我需要参加日期(年份)并将其递增1。我遇到的问题是更换部件。如果同一行中存在重复的matches(两个日期相同),则Replace会匹配它们并替换它们。然后在下一次迭代中通过Matches集合失败,因为匹配的第二个实例不再有效,因为它已被替换。有没有办法只替换我正在迭代的match

这是我的正则表达式: (\|((\d{2})(.)(\w{2,4})(.)(\d{2}))

以下是一些示例文本:

111111|atorvastatin 10 mg tablet|13-AUG-14||13-AUG-14|Sent
222222|atorvastatin 20 mg tablet|30-JAN-13|05-FEB-14|30-JAN-13|Sent
333333|simvastatin 10 mg tablet|30-AUG-13|05-FEB-14|30-AUG-13|Sent
444444|lovastatin 20 mg tablet|21-JUN-13|21-JUN-13|Sent

这是我的代码:

MatchCollection matches = Regex.Matches(line, regexPattern);
foreach(Match match in Matches)
{
  int originalDateYear;
  int newDateYear;
  string replacementValue;

  originalDateYear = Convert.ToInt32(match.Groups[2].Value); //This is the YYYY of the date
  newDateYear = originalDateYear + 1; // Add 1 to the date
  replacementValue = newDateYear.ToString() + match.Groups[3].Value + match.Groups[4].Value + match.Groups[5].Value + match.Groups[6].Value; // Build the new date
  line = line.Replace(match.Groups[1].Value, replacementValue); // Replace the old date with the new date
}

1 个答案:

答案 0 :(得分:1)

您可以使用Regex.Replace重载进行回调:

让我们稍微简化模式:

var regexPattern = new Regex(@"(?<date>\|\d{2}.\w{2,4}.)(?<year>\d{2})");

然后将它用于每一行:

line = regexPattern.Replace(line,
    match => string.Format("{0}{1:00}", match.Groups["date"].Value, int.Parse(match.Groups["year"].Value) + 1);

哦,请注意这里的Y2K错误: - )