簡體   English   中英

替換.NET RegEx Matches集合中的特定匹配項

[英]Replace specific match in .NET RegEx Matches collection

我正在使用C#替換文本文件中的日期值。 我正在逐行解析文件,並嘗試逐個替換日期,因為我需要使用日期(年份)的一部分並將其增加一個。 我遇到的問題在於更換零件。 如果同一行中有重復的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
}

您可以使用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錯誤:-)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM