从 diff 文件中提取路径

Extract paths from a diff file

我正在尝试使用以下代码从 diff 文件中提取路径:

    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);

第一条路径已成功提取,但第二条路径未成功提取。我做错了什么?

输出:

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

预期

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

子字符串定义如下: public string Substring (int startIndex, int length);

第一个很好用,因为 Pos1 是正确的,长度是第一条路径。 第二个正确使用Pos1,但是长度是Path 1 + Path 2.

为了更容易理解:

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);

你会看到第二次的pos2比第一次大很多time.Try

string[] tempStringArray = diff.Split('\n');
string finalStringOne = tempStringArray[0].Replace("--- ","");
string finalStringTwo = tempStringArray[1].Replace("+++ ","");

您还可以使用 Regex-Pattern。例如:

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

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

这样做的好处是,以后如果你想扩展更多的功能,你可以使用那个字符串的其他部分。