Home > Net >  How to get data from simple text line by line
How to get data from simple text line by line

Time:10-29

I am trying to extract data from text. It is larger text. For better understanding. I have simple class Test with one atribute result, which is enum.

class Test{

 private Result result;
 
 public Test(string text){
  this.Result = FindProblem(text);
 }
......

public enum Result
    {
        SUCCESS = 1,
        FAIL = 2,
        NONE = 3

    }


 }

Then I have text:

Today at 01:05: (NAME) Failed Backup - The operation encountered an error. (NAME)
Failed when backing up: A file was not found (NAME)
DISK_OPEN_ERROR

Today at 01:04: (NAME) Successful Backup - Backed 42,73 MB (compressed to 7,32 MB).(Duration: 1 minute)

Today at 00:59: (NAME) Successful Backup - Backed 3,41 GB (compressed to 379,17 MB).(Duration: 4 minutes)

And I want each row to return a Test object with results like: result: Failed or result: Succesful.

Method for returning all objects from text

public Result FindResult(string text)
        {
            var splitText = text.Split("\n").ToList();
            Result r = Result.NONE;
            foreach (var item in splitText)
            {
                if (item.Contains("Failed"))
                {
                    r = Result.FAIL;
                }
                else
                {
                    r = Result.SUCCESS;
                }
            }
            return r;
        }

But it returns only result SUCCESS. Expected output

  result:FAIL
  result:SUCCESS
  result:SUCCESS

CodePudding user response:

What you might do is split on at least 2 newlines, and then map the items in the list using Select and check if it contains "Failed"

If it does, return Result.FAIL, else return Result.SUCCESS so the return type of the function is List<Result>

class Test
{
    private Result result;
    public enum Result
    {
        SUCCESS = 1,
        FAIL = 2,
        NONE = 3    
    }

    public List<Result> FindResult(string text)
    {
         return Regex
        .Split(text, @"\r?\n\s*\r?\n")
        .Select(s => s.Contains("Failed") ? Result.FAIL : Result.SUCCESS)
        .ToList();            
    }
}

And then you can loop the items in the returned list

Test test = new Test();
var results = test.FindResult(input);
foreach(var r in results) {
    Console.WriteLine(r);
}

Output

FAIL
SUCCESS
SUCCESS

See a C# demo.

  • Related