gpt4 book ai didi

c# - 提取两个字符串之间的所有字符串

转载 作者:可可西里 更新时间:2023-11-01 08:30:31 24 4
gpt4 key购买 nike

我正在尝试开发一种方法来匹配两个字符串之间的所有字符串:

我已经试过了,但它只返回第一个匹配项:

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);
}

假设我们有这个字符串

String Text = "A1FIRSTSTRINGA2A1SECONDSTRINGA2akslakhflkshdflhksdfA1THIRDSTRINGA2"

我想要一个执行以下操作的 c# 函数:

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

感谢您的帮助!

最佳答案

    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;
}

关于c# - 提取两个字符串之间的所有字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13780654/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com