如何替换文本文件中的行 [英] How to replace line in text file
本文介绍了如何替换文本文件中的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个文本文件,其中包含一个链接https
I have one text file which contains one link "https"
OBX|39|TX|02580569|1|AM||||||F|||201509171014\r\n
OBX|40|TX|02580569|1|Signed : 09/17/2015 10:14 AM||||||F|||201509171014\r\n
OBX|41|TX|02580569
在该链接之后我想将所有obx数字增加1.
即如果
After that link I want to increase all obx number by 1.
i.e. if
OBX|39|TX|02580569|1|AM|https://
然后低于这一行所有行必须是OBX | 40,OBX | 41等等
并增加1
then below this line all line must be OBX|40, OBX|41 etc
and increased by 1
推荐答案
您可以通过以下方式完成
首先创建一个能找到并提取数字的正则表达式
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);
这篇关于如何替换文本文件中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文