jhdeval jhdeval - 1 month ago 5x
C# Question

C# String processing a non-delimited string to list

Here is an example of the string in question:

[952,M] [782,M] [782] {2[373,M]} [1470] [352] [235] [234] {3[610]}{3[380]} [128] [127]

I have added the spaces but it really does not help the breakdown. What I want to do is take each "field" in square brackets and add it to a string list. The next issue which I can handle is some fields also have a comma separated portion that I can split after the fact. The real problem lies in the Curly braces. For instance
The number outside the square brackets is a repetition of the square brackets.

For the life of me I can not figure out a way where I can consistently split the line into a string list.

Quasi code follows:

for(i = 0 to string.length)
if string.substring(i,1) = "]"
int start1 = i
elseif string.substring(i,1)="["
int start1 = i
elseif string.substring(i,1) = "{"
int start2 = i
elseif string.substring(i,1) = "}"
int end2 = i

I thought about using the code idea above to substring out each "field" but the curly braces also contain the square brackets. Any ideas would be greatly appreciated.

var s = "[952,M] [782,M] [782] {2[373,M]} [1470] [352] [235] [234] {3[610]}{3[380]} [128] [127]";

var s2 = Regex.Replace(s, @"\{(\d+)(\[[^]]+\])\}", m => string.Concat( 
    Enumerable.Repeat(m.Groups[2].Value, int.Parse(m.Groups[1].Value))));

var a = s2.Split("[] ".ToArray(), StringSplitOptions.RemoveEmptyEntries);

// s2 = "[952,M] [782,M] [782] [373,M][373,M] [1470] [352] [235] [234] [610][610][610][380][380][380] [128] [127]"
// a = {"952,M","782,M","782","373,M","373,M","1470","352","235","234","610","610","610","380","380","380","128","127"}