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

本文关键字:空格 分割 字符串 | 更新日期: 2023-09-27 17:50:39

我是正则表达式的新手,我需要一些帮助。我读了一些类似的话题,但我不知道如何解决这个问题。

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

{ 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<string> Result = new List<string>();
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);  
}

谢谢你的帮助!!