基于单词C#拆分字符串数组

时间:2014-06-10 14:21:00

标签: c# regex split string-matching

我有一个字符串数组,格式如下:

      " Number 1 
        asdf asdfn asfm;lamf --- Information
        Number 2
        asdf asdfn asfm;lamf --- Information
        Number 3
        asdf asdfn asfm;lamf --- Information
      "

我必须将整个字符串[]作为单独的字符串数组:

string [] first = " Number 1 
                asdf asdfn asfm;lamf --- Information"


string [] second = " Number 2 
                asdf asdfn asfm;lamf --- Information"

如何使用Regex或Split,以便我可以使用关键字“Number”来拆分字符串数组。请帮帮我!

2 个答案:

答案 0 :(得分:1)

您与string.Split()遇到的问题是它会删除您的分隔符。解决方法可能是重新插入它。

string[] parts = originalString.Split(new[] { "Number" }, StringSplitOptions.None)
    .Select(s => "Number" + s)
    .ToArray();

您仍然需要清理换行符......

答案 1 :(得分:1)

假设您有一个包含原始数据的字符串:

        string testCase =  "Number 1 asdf asdfn asfm;lamf --- Information Number 2 asdf asdfn asfm;lamf --- Information Number 3 asdf asdfn asfm;lamf --- Information";

        string[] numbers = Regex.Split(testCase, "Number").Where(s => s.Trim() != "" && s != "Number").Select(x => "Number" + x).ToArray();

这将是结果:enter image description here