2014-05-09 132 views
-2

我有類似
SOI的字符串; 1; 2; 3; 4; 5; 6; 7; SOI; 8; 9; 10; 11; 12; EOI; 13; EOI;所以我; 14; 15; 16; 17; 18; EOI;分割字符串在C#中使用正則表達式

在這裏,我不得不分割從SOI開始字符串;到EOI;
輸出應該像

[0] - 1; 2; 3; 4; 5; 6; 7; 13;
[1] - 8; 9; 10; 11; 12;
[2] - 14; 15; 16; 17; 18;

我曾嘗試使用以下代碼

string regexexpr = "(?s)(?<=SOI;).+?(?=EOI;)";//@"SOI;(.*?)EOI;"; 
string sText = "SOI; 1; 2; 3; 4; 5; 6; 7;SOI; 8; 9; 10; 11; 12; EOI; 13; EOI; SOI; 14; 15; 16; 17; 18; EOI;"; 
MatchCollection matches = Regex.Matches(sText, @regexexpr); 
var sample = matches.Cast<Match>().Select(m => m.Value); 

分裂但我正在逐漸輸出像
[0] - 1; 2; 3; 4; 5; 6; 7; SOI; 8; 9; 10; 11; 12;
[1] - 14; 15; 16; 17; 18;

請爲我提供更好的解決方案。 感謝

+2

你問如何提取嵌套SOI/EOI結構?如果你可以用正則表達式來做到這一點,我會很驚訝。編寫代碼來處理值列表會更容易 –

+1

等待,您如何期待'[0] - 1; 2; 3; 4; 5; 6; 7; 13;'作爲輸出? '8'來自何處? 9; 10; 11; 12; '去下一場比賽? –

回答

0

我想我會做程序上,而不是使用正則表達式。

編輯:下面的解決方案有錯誤,第一和第三列表是相同的。我要離開它,因爲它可能仍然是一個正確方向的暗示。

1)將一個值設置爲零。
2)讀取字符串中的下一個標記。如果令牌是SOI,則將值1加1;如果令牌爲EOI,則從值
刪除1;如果令牌是數字,則根據值將其添加到不同的數組(或列表)中。
6)GOTO 2

0
private static List<string> GetLists(string sText) 
    { 
     string[] output; 
     List<string> input = new List<string>(); 
     input = sText.Split(new string[] {" "}, StringSplitOptions.RemoveEmptyEntries).ToList(); 
     int count = input.Count(x => x == "SOI;"); 
     output = new string[count]; // set output array to number of lists in string 
     int current = -1; // start with -1 so first SOI will set it on 0 
     int max = -1; 
     foreach (var text in input) 
     { 
      if (text == "SOI;") // set current and max 
      { 
       current++; 
       max++; 
      } 
      else if (text == "EOI;") 
      { 
       current--; 
       if (current == -1) // if u reached -1 it means u are out of any list so set current on max so if u will get "SOI" u will get proper number 
       { 
        current = max; 
       } 
      } 
      else 
      { 
       output[current] += text; 
      } 
     } 

     return output.ToList(); 
    } 
} 
相關問題