I have a comma separated list that could contain blank values, and could contain values wrapped in double-quotes that I do not want to split. I need to create an array using this split so that I can later loop through it.
I've tried using some match regex which works, except it overlooks any null values that I have. I've been trying to use some look ahead regex but I don't think my syntax is working appropriately, as it's returning an array with a length of 1.
This is the match code that most closely shows what I'm going for
var s = 'To, Infinity, "And, Beyond",,Buzz Lightyear';
var array = s.match(/(".*?"|[^",\s]+)(?=\s*,|\s*$)/g);
This is the split syntax which is only returning an array length of 1
var s = 'To, Infinity, "And, Beyond",,Buzz Lightyear';
var array = s.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
With the match function, I expect the output to be:
To
Infinity
And, Beyond
Buzz Lightyear
However, my output is actually
To
Infinity
And, Beyond
Buzz Lightyear
Since you tagged mirth in your question, you can use the built in mirth parser. Note that your exact string from your question won't work because there is a space after the comma and before "And, Beyond." If you are going to quote a CSV field, the entire field needs to be quoted (otherwise the quote is seen as part of the value.)
var serializer = SerializerFactory.getSerializer('delimited');
var s = 'To,Infinity,"And, Beyond",,Buzz Lightyear';
var split = new XML(serializer.toXML(s));
for each (var col in split.row.children()) {
logger.info(col.toString());
}
Edit: I did not produce an array, since you said you only needed it for looping, which is shown above, but if you still need an array you can do:
var arr = [];
for each (var col in split.row.children()) {
arr.push(col.toString());
}