Get a slash except for square brackets

Sample text (I highlighted the desired one /):

pair [@Key = 2] /Elements /Item [Person / Name = 'Martin'] /Date

I am trying to get every slash that is not in the square bracket, can anyone with the help of Regex help me with this? Using:

string[] result = Regex.Split(text, pattern);

I did this with this code, but wondered if it was easier Regex to do the same:

private string[] Split()
{
    List<string> list = new List<string>();
    int pos = 0, i = 0;
    bool within = false;
    Func<string> add = () => Format.Substring(pos, i - pos);
    //string a;
    for (; i < Format.Length; i++)
    {
        //a = add();
        char c = Format[i];
        switch (c)
        {
            case '/':
                if (!within)
                {
                    list.Add(add());
                    pos = i + 1;
                }
                break;
            case '[':
                within = true;
                break;
            case ']':
                within = false;
                break;
        }
    }
    list.Add(add());
    return list.Where(s => !string.IsNullOrEmpty(s)).ToArray();
}
+5
source share
2 answers

using Regex.Matchesmay be a better approach than trying to use split. Instead of specifying a template for separation, you are trying to find the results you need. This works in the main case:

string[] FancySplit(string input) {
    return Regex.Matches(input, @"([^/\[\]]|\[[^]]*\])+")
        .Cast<Match>()
        .Select(m => m.Value)
        .ToArray();
}

:

  • [, ] /
  • [ something ], - /
+2

, :

(?<!\[[^]]+)/

negative lookbehind , , , .

+2

All Articles