Home > database >  Extract paths from a diff file
Extract paths from a diff file

Time:02-22

I am trying to extract the paths from a diff file using below piece of code:

    string diff = "--- //mac/Home/Documents/myFile1.txt\n    //mac/Home/Downloads/myFile2.txt\n@@ -1,1  1,1 @@\n-hol3a2aaaa2!!!!!!\n hol3aaa2!!!!!!";

    int pos1 = diff.IndexOf("--- ");
    int pos2 = diff.IndexOf("\n    ");
    string finalString = diff.Substring(pos1   4, pos2 - 4);
    Console.WriteLine(finalString);
    
    pos1 = diff.IndexOf("    ");
    pos2 = diff.IndexOf("\n@@");
    finalString = diff.Substring(pos1   4, pos2 - 4);
    Console.WriteLine(finalString);

First path is successfully extracted but second isn't. What am I doing wrong?

Output:

//mac/Home/Documents/myFile1.txt
//mac/Home/Downloads/myFile2.txt
@@ -1,1  1,1 @@
-hol3a2aaaa2!!!!!!
 

Expected:

//mac/Home/Documents/myFile1.txt
//mac/Home/Downloads/myFile2.txt

CodePudding user response:

the substring is defined like this: public string Substring (int startIndex, int length);

The first one works out fine because Pos1 is correct and the lenght is the first path. The seconnd one uses Pos1 correct, but the length is Path 1 Path 2.

To make it easier to understand:

string diff = "--- //mac/Home/Documents/myFile1.txt\n    //mac/Home/Downloads/myFile2.txt\n@@ -1,1  1,1 @@\n-hol3a2aaaa2!!!!!!\n hol3aaa2!!!!!!";

int pos1 = diff.IndexOf("--- ");
int pos2 = diff.IndexOf("\n    ");
string finalString = diff.Substring(pos1   4, pos2 - 4);
Console.WriteLine(pos1);
Console.WriteLine(pos2);
Console.WriteLine(finalString);

pos1 = diff.IndexOf("    ");
pos2 = diff.IndexOf("\n@@");
finalString = diff.Substring(pos1   4, pos2 - 4);
Console.WriteLine(pos1);
Console.WriteLine(pos2);
Console.WriteLine(finalString);

You will see pos2 in the second time is much bigger than first time.Try

string[] tempStringArray = diff.Split('\n');
string finalStringOne = tempStringArray[0];
string finalStringTwo = tempStringArray[1];

CodePudding user response:

What else you can use is maybe a Regex-Pattern. E.g.:

(?<= )(.*?)(?=\\n)

or

(?=\/\/)(.*?)(?=\\n)

The advantage is, in the future you can use another parts from that string, if you want to expand more features.

  • Related