Extract all strings between two strings

前端 未结 5 1938
既然无缘
既然无缘 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:28

        private static List ExtractFromBody(string body, string start, string end)
        {
            List matched = new List();
    
            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;
        }
    

提交回复
热议问题