2012-09-28 116 views
0

我需要用分號(;)作爲分隔符分隔字符串。括號內的分號應該被忽略。用分號和分隔符分隔字符串幷包含括號

實施例:

string inputString = "(Apple;Mango);(Tiger;Horse);Ant;Frog;"; 

串的輸出列表應該是:

(Apple;Mango) 
(Tiger;Horse) 
Ant 
Frog 

的其他有效輸入串可以是:

string inputString = "The fruits are (mango;apple), and they are good" 

上述字符串應被劃分到單串

"The fruits are (mango;apple), and they are good" 

string inputString = "The animals in (African (Lion;Elephant) and Asian(Panda; Tiger)) are endangered species; Some plants are endangered too." 

上面的字符串應該被劃分到兩個字符串,如下圖所示:

"The animals in (African (Lion;Elephant) and Asian(Panda; Tiger)) are endangered species" 
"Some plants are endangered too." 

我搜索了很多,但找不到答案,上面的場景。

有沒有人知道如何在不重新發明輪子的情況下實現這個目標?

+0

是。嘗試使用正則表達式 – Reniuz

+0

感謝您的及時答覆。你能給個例子嗎? – user1571734

+0

是否有理由使用分號作爲分隔符?你的結構非常接近[JSON](http://www.w3schools.com/json/default.asp),那爲什麼不使用它呢?沒有任何反對正則表達式,因爲這也會起作用,我只是一個標準支持者。 – iMortalitySX

回答

1

使用正則表達式匹配你想要什麼保持,而不是分隔符:

string inputString = "(Apple;Mango);(Tiger;Horse);Ant;Frog;"; 

MatchCollection m = Regex.Matches(inputString, @"\([^;)]*(;[^;)]*)*\)|[^;]+"); 

foreach (Match x in m){ 
    Console.WriteLine(x.Value); 
} 

輸出:

(Apple;Mango) 
(Tiger;Horse) 
Ant 
Frog 

表達評論:

\(   opening parenthesis 
[^;)]*  characters before semicolon 
(;[^;)]*)* optional semicolon and characters after it 
\)   closing parenthesis 
|   or 
[^;]+  text with no semicolon 

注:表達式上面也接受沒有分號的圓括號中的值,例如(Lark)和多個分號,例如(Lark;Pine;Birch)。它也將跳過空值,例如";;Pine;;;;Birch;;;"將是兩個項目,而不是十個。

+0

謝謝!請試試這個。 – user1571734

+0

上面的正則表達式分割文本「果實是(芒果;蘋果),它們很好」兩個字符串。實際上,它應該是一個。 – user1571734

+0

@ user1571734:我看到了,改變了規格。 ;)在圓括號前後添加條件集,並重復圓括號和後面的集:「@」[^;] * \(([^;)] *(; [^;)] *)* \) [^] *)+ | [^] +「'。 – Guffa

0

與「正常」情況分開處理被隔離的案件,以確保前者中省略分號。

一個正則表達式實現這一目標(匹配您輸入的單個元素)可能看起來像下面的(未測試):

"\([A-Za-z;]+\)|[A-Za-z]+" 
相關問題