Convert a string like "1,2-5,36" etc, to array [1,2,3,4,5,36]

Hello,

I am attempting to perform something like this:

stackoverflow.com/questions/7698664/converting-a-range-or-partial-array-in-the-form-3-6-or-3-6-12-into-an-arra

I want to convert a string like “1,3-5,8-10” to an array [1,3,4,5,8,9,10]. I have looked at the regexp and regexp2, and can match the digits, but am having trouble creating the range between the digits. The link shows it done in php, but I cannot find any squirrel examples.

Thanks!

This is my shot at it … and I did test it.

Not sure if this is the most efficient though …

`function parse(string1){
    local data1=split(string1,",");
    local build="";
        foreach (count, value in data1) {
        local sr=value;
    	local ex = regexp("[-]");
            if(ex.search(value)){
            local data2=split(value,"-");
            sr=data2[0].tointeger();
            local st=data2[1].tointeger();
                while(sr<=st){
                build=build+sr+",";
                sr++;
                }
        }
        else{
        build=build+sr+",";   
        }
}
local results=split(build,",");
foreach(val in results)
    server.log("value="+val+"\
");

}

local test1="1,3-5,8-10,21,43";
parse(test1)`

Here is my log result:
2016-06-15 18:34:27 UTC-5 [Status] Agent restarted: reload.
2016-06-15 18:34:27 UTC-5 [Status] Downloading new code; 4.53% program storage used
2016-06-15 18:34:27 UTC-5 [Device] value=1
2016-06-15 18:34:27 UTC-5 [Device] value=3
2016-06-15 18:34:27 UTC-5 [Device] value=4
2016-06-15 18:34:27 UTC-5 [Device] value=5
2016-06-15 18:34:27 UTC-5 [Device] value=8
2016-06-15 18:34:27 UTC-5 [Device] value=9
2016-06-15 18:34:27 UTC-5 [Device] value=10
2016-06-15 18:34:27 UTC-5 [Device] value=21
2016-06-15 18:34:27 UTC-5 [Device] value=43

I reckon you could do this with just 2 splits. Not a lot of error checking with this. Probably should be enclosed with try/catch

`
myString <- "1,2-5,36"
result <- []

foreach(n in split(myString,",")) {
local range = split(n,"-")
if (range.len()==1)
result.push(n.tointeger())
else
for ( local val=range[0].tointeger();val<=range[1].tointeger();val++)
result.push(val)
}

//to test
server.log(“result=”+http.jsonencode(result))
`

I was trying to use regexp to find digits before and after the - match… but string split is much simpler. Thanks guys!