Extract all strings between two strings
c#
Solution
private static List<string> ExtractFromBody(string body, string start, string end)
{
List<string> matched = new List<string>();
int indexStart = 0;
int indexEnd = 0;
bool exit = false;
while (!exit)
{
indexStart = body.IndexOf(start);
if (indexStart != -1)
{
indexEnd = indexStart + body.Substring(indexStart).IndexOf(end);
matched.Add(body.Substring(indexStart + start.Length, indexEnd - indexStart - start.Length));
body = body.Substring(indexEnd + end.Length);
}
else
{
exit = true;
}
}
return matched;
}
Problem
I'm trying to develop a method that will match all strings between two strings: I've tried this but it returns only the first match: ``` string ExtractString(string s, string start,string end) { // You should check for errors in real-world code, omitted for brevity int startIndex = s.IndexOf(start) + start.Length; int endIndex = s.IndexOf(end, startIndex); return s.Substring(startIndex, endIndex - startIndex); } ``` Let's suppose we have this string ``` String Text = "A1FIRSTSTRINGA2A1SECONDSTRINGA2akslakhflkshdflhksdfA1THIRDSTRINGA2" ``` I would like a c# function doing the following : ``` public List<string> ExtractFromString(String Text,String Start, String End) { List<string> Matched = new List<string>(); . . . return Matched; } // Example of use ExtractFromString("A1FIRSTSTRINGA2A1SECONDSTRINGA2akslakhflkshdflhksdfA1THIRDSTRINGA2","A1","A2") // Will return : // FIRSTSTRING // SECONDSTRING // THIRDSTRING ``` Thank you for your help !