gpt4 book ai didi

c# - 如何在不丢失其在 C# 中的部分的情况下真正将字符串拆分为字符串数组?

转载 作者:太空狗 更新时间:2023-10-30 01:06:00 25 4
gpt4 key购买 nike

我有什么

string ImageRegPattern = @"http://[\w\.\/]*\.jpg|http://[\w\.\/]*\.png|http://[\w\.\/]*\.gif";
string a ="http://www.dsa.com/asd/jpg/good.jpgThis is a good dayhttp://www.a.com/b.pngWe are the Best friendshttp://www.c.com";

我想要什么

string[] s;
s[0] = "http://www.dsa.com/asd/jpg/good.jpg";
s[1] = "This is a good day";
s[2] = "http://www.a.com/b.png";
s[3] = "We are the Best friendshttp://www.c.com";

奖励:
如果 url 可以像下面这样拆分,那就更好了,但如果不能,那也没关系。

s[3] = "We are the Best friends";
s[4] = "http://www.c.com";

问题是什么
我尝试使用下面的代码来拆分字符串,

string[] s= Regex.Split(sourceString, ImageRegPattern, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);

但是效果并不好,似乎Split方法把匹配ImageRegPattern的字符串全部取出来了。但我希望他们留下来。我查看了 MSDN 上的 RegEx 页面,似乎没有合适的方法来满足我的需要。那怎么办呢?

最佳答案

你需要类似这个方法的东西,它首先找到所有匹配项,然后将它们连同它们之间不匹配的字符串一起收集到一个列表中。

更新:如果未找到匹配项,则添加条件处理。

private static IEnumerable<string> InclusiveSplit
(
string source,
string pattern
)
{
List<string> parts = new List<string>();
int currIndex = 0;

// First, find all the matches. These are your separators.
MatchCollection matches =
Regex.Matches(source, pattern,
RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);

// If there are no matches, there's nothing to split, so just return a
// collection with just the source string in it.
if (matches.Count < 1)
{
parts.Add(source);
}
else
{
foreach (Match match in matches)
{
// If the match begins after our current index, we need to add the
// portion of the source string between the last match and the
// current match.
if (match.Index > currIndex)
{
parts.Add(source.Substring(currIndex, match.Index - currIndex));
}

// Add the matched value, of course, to make the split inclusive.
parts.Add(match.Value);

// Update the current index so we know if the next match has an
// unmatched substring before it.
currIndex = match.Index + match.Length;
}

// Finally, check is there is a bit of unmatched string at the end of the
// source string.
if (currIndex < source.Length)
parts.Add(source.Substring(currIndex));
}

return parts;
}

您的示例输入的输出将如下所示:

[0] "http://www.dsa.com/asd/jpg/good.jpg"
[1] "This is a good day"
[2] "http://www.a.com/b.png"
[3] "We are the Best friendshttp://www.c.com"

关于c# - 如何在不丢失其在 C# 中的部分的情况下真正将字符串拆分为字符串数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16821471/

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