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 Extract
This is a generic solution, and I believe more readable code. Not tested, so beware.
public static IEnumerable> SplitBy(this IEnumerable source,
Func startPredicate,
Func endPredicate,
bool includeDelimiter)
{
var l = new List();
foreach (var s in source)
{
if (startPredicate(s))
{
if (l.Any())
{
l = new List();
}
l.Add(s);
}
else if (l.Any())
{
l.Add(s);
}
if (endPredicate(s))
{
if (includeDelimiter)
yield return l;
else
yield return l.GetRange(1, l.Count - 2);
l = new List();
}
}
}
In your case you can call,
var text = "A1FIRSTSTRINGA2A1SECONDSTRINGA2akslakhflkshdflhksdfA1THIRDSTRINGA2";
var splits = text.SplitBy(x => x == "A1", x => x == "A2", false);
This is not the most efficient when you do not want the delimiter to be included (like your case) in result but efficient for opposite cases. To speed up your case one can directly call the GetEnumerator and make use of MoveNext.