2017-01-26 30 views
0

我有看起來像這樣的字符串。每行都是\r分隔,爲了視覺目的放置在這裏。使用已知密鑰按分組劃分文本

BEGIN_SECTIONS_INFORMATION 
NUMSECTIONS=6 
SECTION_GROUPNAME[1]=GROUP_1 
SECTION_NAME[1]=foo 
BEGIN_SECTION[1] 
//blah... 
END_SECTION[1] 
SECTION_GROUPNAME[2]=GROUP_2 
SECTION_NAME[2]=bazzz 
BEGIN_SECTION[2] 
//blah... 
END_SECTION[2] 
END_SECTIONS_INFORMATION 

我需要SECTION_GROUPNAME拆分此字符串轉換成IEnumerable<T>這樣的:

指數0:

SECTION_GROUPNAME[1]=GROUP_1 
SECTION_NAME[1]=foo 
BEGIN_SECTION[1] 
//blah... 
END_SECTION[1] 

指數1:

SECTION_GROUPNAME[2]=GROUP_2 
SECTION_NAME[2]=bazzz 
BEGIN_SECTION[2] 
//blah... 
END_SECTION[2] 

規則:

  • 每節以SECTION_GROUPNAME[n]開頭。
  • 每節有一個SECTION_NAME[n]並有一個BEGIN_END_
  • 部分名稱是唯一的。

我曾嘗試:

var sections = from line in sectionGroups 
       where line.StartsWith("SECTION_GROUPNAME") 
       group line by "SECTION_GROUPNAME"; 

也試過

var sections = sectionGroups.Split(new string[] { "SECTION_GROUPNAME" }, StringSplitOptions.None); 

this post,OP創建團體枚舉/列表。我不能這樣做,因爲我不知道字符串中會有多少組/部分。

+0

你只想找一個'IEnumerable的'和假設myEnumerable [N]匹配SECTION_GROUPNAME [N],或者你希望也從中提取的關鍵文本?如果是後者,你在尋找什麼關鍵。如果前者,爲什麼你的分手不適合你?你不能只是將SECTION_GROUPNAME追加到每個結果字符串的開頭嗎? – Kolichikov

+0

我的分割結果在SECTION_GROUPNAME之前的所有內容(第一個,後面的所有分割都沒有分割)以及之後的所有內容。 – Kyle

回答

2

假設您想要一個包含您描述的所有內容而沒有關鍵結構的字符串的IEnumerable<T>

基本的想法是刪除你不想要的東西(開始和結束位),然後通過所需字符串的開始進行拆分。最後,分割文本不會將其放入結果數組中,因此您必須手動將其添加回來。

以下爲我工作:

static string s = @"BEGIN_SECTIONS_INFORMATIONNUMSECTIONS=6SECTION_GROUPNAME[1]=GROUP_1SECTION_NAME[1] = foo\rBEGIN_SECTION[1]\rEND_SECTION[1]\rSECTION_GROUPNAME[2]=GROUP_2SECTION_NAME[2] = bazzzBEGIN_SECTION[2]END_SECTION[2]END_SECTIONS_INFORMATION"; 


static void Main(string[] args) 
{ 
    var withoutEnd = s.Split(new[] {"END_SECTIONS_INFORMATION"}, StringSplitOptions.RemoveEmptyEntries); 
    var SplitItems = withoutEnd[0].Split(new[] { "SECTION_GROUPNAME"}, StringSplitOptions.None).ToList(); 
    SplitItems.RemoveAt(0); //the first part is just the introduction 
    var result = SplitItems.Select(x => "SECTION_GROUPNAME" + x); 

}