Home » Java » c# – Split string on the '.' dot characters that are not inside of [] brackets-Exceptionshub

c# – Split string on the '.' dot characters that are not inside of [] brackets-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have some string like:

"Item.ObjectA.ObjectBs[Id=1234;Name=Test;Date=12.05.2016 11:11:11].ObjectD.Value"

If I split it with . It gives:

Item

ObjectA

ObjectBs[Id=1234;Name=Test;Date=12

05

2016 11:11:11]

ObjectD

Value

But I want a result, ignoring the dots inside [], which is:

Item

ObjectA

ObjectBs[Id=1234;Name=Test;Date=12.05.2016 11:11:11]

ObjectD

Value

How can i simply achieve this?

How to&Answers:

Moving my comment to an answer:

One option is to use a negative lookahead in order to match . characters that are not followed by zero or more [ characters and then a ] character:

\.(?![^[]*\])

Live Example:

string pattern = @"\.(?![^[]*\])";
string input = "Item.ObjectA.ObjectBs[Id=1234;Name=Test;Date=12.05.2016 11:11:11].ObjectD.Value";

foreach (String split in Regex.Split(input, pattern))
{
    Console.WriteLine(split);
}

Output:

Item

ObjectA

ObjectBs[Id=1234;Name=Test;Date=12.05.2016 11:11:11]

ObjectD

Value


Alternatively, instead of splitting the string, you could also match based on the following expression:

[^.]*\[[^]]*\]|[^.]*

Live Example:

string pattern = @"[^.]*\[[^]]*\]|[^.]*";
string input = "Item.ObjectA.ObjectBs[Id=1234;Name=Test;Date=12.05.2016 11:11:11].ObjectD.Value";
foreach (Match match in Regex.Matches(input, pattern))
{
    Console.WriteLine(match.Value);
}

Same output.

Answer:

This answer shows how to do it in pure programming

using System;
using System.Collections.Generic;                   
using System.Text;
using System.Linq;

public class Program
{

    public static void Main()
    {

        var orig = "Item.ObjectA.ObjectBs[Id=1234;Name=Test;Date=12.05.2016 11:11:11].ObjectD.Value";

        var parts = new List<string>();
        var stop = false;
        var current = new StringBuilder();

        for (int i = 0; i < orig.Length; i++)
        {

            if (orig[i] != '.')
                current.Append(orig[i]);

            if (orig[i] == '[')
                stop = true;

            if (orig[i] == ']')
                stop = false;

            if ((orig[i] == '.' && !stop) || i == orig.Length - 1)
            {
                parts.Add(current.ToString());
                current.Length = 0;
            }


        }

        parts.ForEach(x =>  Console.WriteLine(x));
    }
}

Result

Item
ObjectA
ObjectBs[Id=1234;Name=Test;Date=12052016 11:11:11] ObjectD
Value