从 diff 文件中提取路径
我正在尝试使用下面的代码从 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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
子字符串定义如下:
公共字符串子字符串(int startIndex,int length);
第一个效果很好,因为 Pos1 是正确的,并且长度是第一条路径。
第二次使用Pos1正确,但长度是Path 1 + Path 2。
为了更容易理解:
你会看到第二次的pos2比第一次大得多。尝试一下
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:
You will see pos2 in the second time is much bigger than first time.Try
您还可以使用的也许是正则表达式模式。例如:
or
优点是,将来如果您想扩展更多功能,可以使用该字符串中的其他部分。
What else you can use is maybe a Regex-Pattern. E.g.:
or
The advantage is, in the future you can use another parts from that string, if you want to expand more features.