My input string:
var s = "{1, >, [4,6,7,8], a, b, [x,y], d, 9}";
I'd like to remove the {} and get an array with each element separated by a comma EXCEPT when the comma is inside [] -- basically anything in brackets will be returned as its own element without the brackets.
Desired output List< String > or String[] whose contents are:
1
>
4,6,7,8
a
b
x,y
d
9
ETA: Here is my UnitText (xunit), which tests each of the patterns suggested by @washington-guedes, with a parameter to trim the input string of whitespaces. The test fails on both cases when the WS is cleaned.
[Theory]
[InlineData(@"([^{\s]+(?=(?:,|})))", false)]
[InlineData(@"([^{\s]+(?=(?:,|})))", true)]
[InlineData(@"([^{\s[\]]+(?=(?:]|,|})))", false)]
[InlineData(@"([^{\s[\]]+(?=(?:]|,|})))", true)]
public void SO(string pattern, bool trimWS)
{
//Arrange
var exp = "{1, >, [4,6,7,8], a, b, [x,y], d, 9}";
if (trimWS)
exp = exp.Replace(" ", "");
Match match = Regex.Match(exp, pattern);
var list = new List<String>();
while (match.Success)
{
list.Add(match.Value);
match = match.NextMatch();
}
Assert.Equal(8, list.Count);
}
[...]be nested? And are there always spaces between the different major elements? Because right now, it seems like you can just remove the starting'{'and ending'}', split by", ", and then remove any'['s and']'s.