Regex 将文件开头与字符串文字匹配
我正在使用一个多行文本块,我需要将所有内容分成3组Regex 将文件开头与字符串文字匹配,regex,Regex,我正在使用一个多行文本块,我需要将所有内容分成3组 1: beginning of the file up to a string literal // don't keep 2: The next line //KEEP THE LINE FOLLOWING STRING LITERAL 3: Everything following that line to the end of file. // don't keep << aFirstLing here aSeco
1: beginning of the file up to a string literal // don't keep
2: The next line //KEEP THE LINE FOLLOWING STRING LITERAL
3: Everything following that line to the end of file. // don't keep
<<
aFirstLing here
aSecondLine here
MyStringLiteral //marks the next line as the target to keep
What I want to Keep!
all kinds of crap that I don't
<<
1:文件开头到字符串文字//不保留
2:下一行//保留字符串后面的行
3:从那一行到文件末尾的所有内容。//不要老是抱怨
File.ReadAllLines()将为您提供一个数组,您可以对该数组进行迭代,直到找到文本,然后执行下一行
string[] lines = File.ReadAllLines();
for(int i;i<lines.Length;i++)
{
if(line == Literal)
return lines[i + 1];
}
string[]lines=File.ReadAllLines();
对于(int i;i而言,与其将整个文件读取到内存中,不如读取所需的内容:
List<string> TopLines = new List<string>();
string prevLine = string.Empty;
foreach (var link in File.ReadLines(filename))
{
TopLines.Add(line);
if (prevLine == Literal)
{
break;
}
prevLine = line;
}
或者,如果字符串已在列表中:
TopLines = lines.TakeWhile(s => s != Literal).ToList();
TopLines.Add(Literal);
.*(^mystringlateral\r?\n)([\w|\s][^\r\n]+)(.+)似乎有效。诀窍不是反向引用-而是排除了\r\n。对“ReadLines”的建议将不起作用(开箱即用)文本块不在外部文件中-我已将电子邮件正文拉入我的应用程序。感谢您的后续操作。希望看到与代码片段类似的Linq。
TopLines = lines.TakeWhile(s => s != Literal).ToList();
TopLines.Add(Literal);