Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
545 views
in Technique[技术] by (71.8m points)

c# - 尝试从以给定变量开头和结尾的文本文件中获取(Trying to get from a text file that starts with and ends with given variables)

Both the below cases are not working.

(以下两种情况均无效。)

I want to extract from a text file a certain part that I can choose by specifying the start of the line and end.

(我想从文本文件中提取可以通过指定行的开头和结尾来选择的特定部分。)

  1. case looks like this:

    (情况如下:)

using (StreamReader reader = new StreamReader("C:/Users/david/Desktop/20180820.log",Encoding.Default))
{
    Console.WriteLine("From:");
    string a = (Console.ReadLine());
    Console.WriteLine(" To:");
    string b = (Console.ReadLine());   
    while (!reader.EndOfStream)
    {
        var line = reader.ReadLine();
        if (line.StartsWith(a) && (line.EndsWith(b)))
        {
            Console.WriteLine(line);
        }
    }
}
  1. case with regex

    (正则表达式)

string line;
while ((line = reader.ReadLine()) != null)
{
    string regex12 = a.ToString() + b.ToString(); 
    Match m = Regex.Match(line,regex12);
    string s = Regex.Match(line, regex12).Groups[0].Value;
    Console.WriteLine(s);
    if (m.Success) 
    {
        string n = m.Groups[0].Value;
        Console.WriteLine(n);
    }
}

If anyone can solve my problem, I will be very thankful.

(如果任何人都能解决我的问题,我将非常感激。)

  ask by David translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could do the following.

(您可以执行以下操作。)

var reader = File.OpenText(filePAth);
var startLineDetected = false;
var startWord = // startWord;
var endWord =  // endWord;
var strBuilder = new StringBuilder();
while(!reader.EndOfStream)
{
    var newLine = reader.ReadLine();


    if(newLine.Contains(startWord) && !startLineDetected)
    {
        startLineDetected = true;
        newLine = newLine.Substring(newLine.IndexOf(startWord));
    }

    if(newLine.Contains(endWord) && startLineDetected)
    {
        newLine = newLine.Substring(0,newLine.IndexOf(endWord) + endWord.Length);
        strBuilder.Append(newLine);
        break;
    }


    if(startLineDetected)
    {
        strBuilder.Append(newLine);
    }
}
var resultData = strBuilder.ToString();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...