split a string only on spaces that are outside curly braces

前端 未结 3 1112
耶瑟儿~
耶瑟儿~ 2021-01-16 17:11

I am new to regex and I need some help. I read some topics similar to this issue, but I could not figure out how to resolve it.

I need to split a string on every bla

相关标签:
3条回答
  • 2021-01-16 17:23
    \{[^}]+\}|\S+
    

    This matches either a run of any characters enclosed by curly braces, or a run of non-space characters. Grabbing all of the matches for it out of your string should provide you with what you want.

    0 讨论(0)
  • 2021-01-16 17:25

    Here is exactly what you want...

    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());
    
    0 讨论(0)
  • 2021-01-16 17:27

    I solved my problem using:

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

    Thanks for your help guys !!!

    0 讨论(0)
提交回复
热议问题