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

标签 c# regex arrays string split

我有什么

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/

相关文章:

python - 使用替换的正则表达式来转换数字

带有十二面体顶点的java数组

代码不断崩溃(第 4.2 周已停止工作

c# - float 变量格式

c# - 泛型、继承和新运算符

c# - Asp.net 中的全局函数

java - 正则表达式验证字符串中是否有 4 个不同的字符

c# - 从字符串中获取大写字母的索引

arrays - 如何使我的代码成为可重用的组件?

c# - 调试时可视化 DataTable 的最佳方法是什么?