Extract all strings between two strings

前端 未结 5 1971
既然无缘
既然无缘 2020-11-28 12:44

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         


        
5条回答
  •  醉酒成梦
    2020-11-28 13:35

    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.

提交回复
热议问题