在.txt文件中搜索特定行,并将其复制到另一个文件c#中
本文关键字:文件 复制 另一个 搜索 txt | 更新日期: 2023-09-27 17:53:43
我有一个内容如下的。txt文件,例如:
1
Hey, how are u
Ist everything ok ?
I hope u are well
2 I'm fine thanks
Nice to hear from u
3 Sounds great
What are u doing now ?
Hope u enjoy your stay
我需要一个方法,我可以给一个数字,例如2和程序应该复制整个文本后的数字2,直到数字3在一个新的txt文件。楼下我张贴了一个解决方案如何识别行,但现在我不知道如何复制文件的某一部分
public static void RunSnippet()
{
string input =
"1 Hey, how are u'n" +
"'n" +
"2 I'm fine thanks'n" +
"'n" +
"3 Sounds great";
Console.WriteLine(GetLine(3, input));
}
static string GetLine(int number, string content)
{
return Regex.Split(content, "'n").First(l=> l.StartsWith(number.ToString()));
}
使用正则表达式
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string input =
"1 Hey, how are u'n" +
"'n" +
"2 I'm fine thanks'n" +
"'n" +
"3 Sounds great";
string pattern = @"^(?'index''d+)'s+(?'value'.*)";
Regex expr = new Regex(pattern, RegexOptions.Multiline);
MatchCollection matches = expr.Matches(input);
Dictionary<int, string> dict = new Dictionary<int, string>();
foreach(Match match in matches)
{
dict.Add(int.Parse(match.Groups["index"].Value), match.Groups["value"].Value);
}
string sentence2 = dict[2];
}
}
}