如何获得两个字符串之间的字符串,其中两个字符串是重复的?
问题描述:
鉴于n行的字符串,如:如何获得两个字符串之间的字符串,其中两个字符串是重复的?
启动学生 - 主题 - 最终学生 - 启动学生的标志,最终以学生 - 启动 - 学生总最终学生 - 学生的名字 - 学生的详细信息 - 百分比 - 结束 - 学生的详细信息 - 开始 - 学生 - 主题 - 结束 - 学生 - 开始 - 学生 - 结束 - 学生 - - 开始 - 学生 - 总计 - 结束 - 学生-class - 开始 - 学生比例,最终以学生
我的方法:
string s = File.ReadAllText(@"D:\Data.txt");
int start = s.IndexOf("start-student") + 1;
int end = s.IndexOf("end-student", start);
string result = s.Substring(start, end - start);
Console.WriteLine(result);
我得到只有一个字符串:
“主题”
由于提前
答
就可以解决这个使用正则表达式:
using System;
using System.IO;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string s = File.ReadAllText(@"D:\Data.txt");
var matches = Regex.Matches(s, "(?<=start-student)((?!end-student).)*");
foreach(var m in matches)
{
Console.Out.WriteLine(m);
}
}
}
主要生产
- 主题 -
-marks-
-total-
-subject-
-marks-
-total-
-percentage-
+0
以上代码正在工作,我也发现下面的代码工作正常 谢谢你的帮助 – user3544385
答
string s = File.ReadAllText(@"D:\SampleXML.txt");
Regex r = new Regex(@"start-student-(.+?)-end-student");
MatchCollection mc = r.Matches(s);
string[] c = new string[mc.Count];
for (int i = 0; i < mc.Count; i++)
{
c[i] = mc[i].Groups[0].Value;
}
string result = string.Join("\n", c);
Console.WriteLine(result);
使用您的代码我得到“挞 - 学生 - subject--”。你确定你问的是正确的问题,因为你得到的数据是非常随机的。 –
这里没有任何循环,所以当然你只会得到一个结果。你需要帮助理解循环? – BradleyDotNET