仅在花括号外的空格上分割字符串

我是正则表达式的新手,我需要一些帮助。 我读了一些类似于这个问题的主题,但我无法弄清楚如何解决它。

我需要在不在一对花括号内的每个空格上分割一个字符串。 花括号外的连续空格应视为单个空格:

{ TEST test } test { test test} {test test } { 123 } test test 

结果:

 { TEST test } test { test test} {test test } { 123 } test test 

 \{[^}]+\}|\S+ 

这匹配由花括号括起来的任何字符的运行,或者一系列非空格字符。 从你的字符串中抓取所有匹配项应该可以为你提供你想要的东西。

这正是你想要的……

 string Source = "{ TEST test } test { test test} {test test } { 123 } test test"; List Result = new List(); StringBuilder Temp = new StringBuilder(); bool inBracket = false; foreach (char c in Source) { switch (c) { case (char)32: //Space if (!inBracket) { Result.Add(Temp.ToString()); Temp = new StringBuilder(); } break; case (char)123: //{ inBracket = true; break; case (char)125: //} inBracket = false; break; } Temp.Append(c); } if (Temp.Length > 0) Result.Add(Temp.ToString()); 

我解决了我的问题:

 StringCollection information = new StringCollection(); foreach (Match match in Regex.Matches(string, @"\{[^}]+\}|\S+")) { information.Add(match.Value); } 

谢谢你的帮助!