[英]Find and replace file lines
I have a text file with over 12,000 lines. 我有一个超过12,000行的文本文件。 In that file I need to replace certain lines.
在该文件中,我需要替换某些行。 Some lines begin with a
;
有些行以a开头
;
, some have random words, some start with space. ,有些有随机词,有些则以空格开头。 However, I am only concerned with the two types of lines I describe below.
但是,我只关注下面描述的两种类型的线。
I have a line like 我有一条线
SET avariable:0 ;Comments
and I need to replace it to look like 我需要将其替换为外观
set aDIFFvariable:0 :Integer // comments
The only CASE that is necessary is in the word Integer
I
needs to be capitalized. 唯一需要的CASE是
Integer
这个词, I
需要大写。
I also have 我也有
String aSTRING(7) ;Comment
that needs to look like 需要看起来像
STRING aSTRING(7) :array [0..7] of AnsiChar; // Comments
I need to keep all the spacing the same. 我需要保持所有间距相同。
Here is what I have so far 这是我到目前为止所拥有的
static void Main(string[] args)
{
string text = File.ReadAllText("C:\\old.txt");
text = text.Replace("old text", "new text");
File.WriteAllText("C:\\new.txt", text);
}
I think I need to use REGEX, which I have tried to make for my first example: 我想我需要使用REGEX,我试图为我的第一个例子:
\\s\\s[set]\\s*{4}.*[:0]\\s*[;].*
<-- I now know this is invalid - please advise \\s\\s[set]\\s*{4}.*[:0]\\s*[;].*
< - 我现在知道这是无效的 - 请告知
I need help with properly setting up my program to find and replace those lines. 我需要帮助才能正确设置程序以查找和替换这些行。 Should I read one line at a time and if it matches then do something?
我应该一次读一行,如果匹配,那么做点什么? I am confused really as to where to start.
我真的很困惑从哪里开始。
BRIEF pseudo code of what I want to do 简要说明我想做什么的伪代码
//open file
//step through file
//if line == [regex] then add/replace as needed
//else, go to next line
//if EOF, close file
Taking a stab at this separately because each line is so radically different that capturing both in the same expression will be a nightmare. 分别对此进行一次攻击,因为每条线都是如此完全不同,以便在同一个表达中捕获两者都将是一场噩梦。
To match your first example and replace it: 要匹配您的第一个示例并替换它:
String input = "SET avariable:0 ;Comments";
if (Regex.IsMatch(input, @"\s?(set)\s*(\w+):?(\d)\s+;?(.*)?"))
{
input = Regex.Replace(input, @"\s?(set)\s*(\w+):?(\d)\s+;?(.*)?", "$1 $2:$3 :Integer // $4";
}
Give that a shot (Play with it here: http://regex101.com/r/zY7hV2 ) 给它一个镜头(在这里玩它: http : //regex101.com/r/zY7hV2 )
To match your second example and replace it: 要匹配您的第二个示例并替换它:
String input = "String aSTRING(7) ;Comments";
if (Regex.IsMatch(input, @"\s?(string)\s*(\w+)\((\d)\)\s*;(.*)"))
{
input = Regex.Replace(input, @"\s?(string)\s*(\w+)\((\d)\)\s*;(.*)", "$1 $2($3) :array [0..$3] of AnsiChar; // $4";
}
And play around with this one here: http://regex101.com/r/jO5wP5 在这里玩这个: http : //regex101.com/r/jO5wP5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.