C# 获取可在C中重复的两个字符串之间的字符串#

C# 获取可在C中重复的两个字符串之间的字符串#,c#,C#,这个话题我看了很多遍了 获取两个字符串之间的字符串 但我并没有发现怎样才能在整个文本中得到两个字符串之间的字符串 例如,我有文本 关键1 这里是随机文本 另一个随机文本 键2 这里是随机文本 这里是随机文本 这里是随机文本 关键1 又是一些文字 键2 所以我想让程序得到介于key1和key2之间的文本,所以输出应该如下 随机发短信给她 另一个随机文本 又是一些文字 我用了下面的方法 但它只从上面的键1和键2获取第一个文本。所以我想让程序得到这两个单词(key1和key2)之间的每个key1和ke

这个话题我看了很多遍了

获取两个字符串之间的字符串

但我并没有发现怎样才能在整个文本中得到两个字符串之间的字符串 例如,我有文本

关键1

这里是随机文本

另一个随机文本

键2

这里是随机文本

这里是随机文本

这里是随机文本

关键1

又是一些文字

键2

所以我想让程序得到介于key1key2之间的文本,所以输出应该如下

随机发短信给她

另一个随机文本

又是一些文字 我用了下面的方法

但它只从上面的键1和键2获取第一个文本。所以我想让程序得到这两个单词(key1和key2)之间的每个key1和key2文本


对不起,我的英语不好

找到了答案。正是我想要的。谢谢所有支持我的人

   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;
            }
私有静态列表ExtractFromBody(字符串主体、字符串开始、字符串结束)
{
列表匹配=新列表();
int indexStart=0;
int indexEnd=0;
bool exit=false;
当(!退出)
{
indexStart=body.IndexOf(开始);
如果(indexStart!=-1)
{
indexEnd=indexStart+body.Substring(indexStart.IndexOf(end));
Add(body.Substring(indexStart+start.Length,indexEnd-indexStart-start.Length));
body=body.Substring(indexEnd+end.Length);
}
其他的
{
退出=真;
}
}
返回匹配;
}

找到第一个匹配项后,您需要组织一个循环以继续搜索。@Sinatr否,这不起作用
   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;
            }