且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何替换文本文件中的行

更新时间:2023-02-23 14:36:06

您可以通过以下方式完成



首先创建一个能找到并提取数字的正则表达式

You can do it in the following way

First create a regular expression that will find and extract the numbers
private static Regex obxExpr = new Regex(@"^OBX\|(?<val>[0-9]+)\|", RegexOptions.IgnoreCase | RegexOptions.Multiline);





然后创建替换方法



Then create a replacement method

private string IncrementNumber(Match m)
{
    // Extract the number
    int number = int.Parse(m.Groups["val"].Value);
    // Increment by 1
    number++;
    // Replace the old number with the new
    string retval = m.Value.Replace(m.Groups["val"].Value, number.ToString());

    return retval;
}





最后



And finally

// input data used for debugging. This will be your file content           
string input = @"OBX|39|TX|02580569|1|AM|https://|||||F|||201509171014\r\n
OBX|40|TX|02580569|1|Signed     : 09/17/2015 10:14 AM||||||F|||201509171014\r\n
OBX|41|TX|02580569";

// find https in the string. If not found set the index to 0
int index = input.IndexOf("https:");
if (index < 0)
    index = 0;

// Start the replacement after the link if found
string modInput = input.Substring(index);
// This will find all occurrences of OBX|nn| and increment nn by 1
string replaced = obxExpr.Replace(modInput, new MatchEvaluator(IncrementNumber));
// Concatenate the first part of the string with the rest
string output = input.Substring(0, index) + replaced;
// Write the contents to a file
File.WriteAllText(@"C:\Some\Where\On\Your\Hard\Drive\file.txt", output);