2012-09-28 118 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]+" 
相关问题