Optimizing regex alternation, ability to view which choice matched? So I've got a regular expression parsing tcp responses from a music daemon. In case responses pile up I've come up with an expression to separate full responses from the data, however I'd like to also reference which choice was matched. Using capturing groups results in different numbers for each group, so is there a way to reference which alternation choice was matched besides that?

var patt = /((volume):\s\d+\n(.+\n)+?OK\n|OK\s(MPD)\s\d+\.\d+\.\d+|(OK)|(ACK).+\n)/;


This will match it, but I want to do different things with the separated response based on which match it was. I'd like to just have a switch case reference a single variable, but the only way I can think of to is:

var mycase = null;
var result = patt.exec(data);
if (result[2] == "volume")
    mycase= "volume";
else if (result[4] == "MPD")
    mycase= "MPD";
else if (result[5] == "OK")
    mycase= "OK";
else if (result[6] == "ACK")
    mycase= "ACK";


Is there a better way to do this?
First of all you can use non capturing groups to simplify the indices

var patt = /(?:(volume):\s\d+\n(?:.+\n)+?OK\n|OK\s(MPD)\s\d+\.\d+\.\d+|(OK)|(ACK).+\n)/;

var mycase = null;
var result = patt.exec(data);
if (result[1] == "volume")
    mycase= "volume";
else if (result[2] == "MPD")
    mycase= "MPD";
else if (result[3] == "OK")
    mycase= "OK";
else if (result[4] == "ACK")
   mycase= "ACK";


With this the result of the regex will be one of these

[ "complete match",  "volume", undefined, undefined, undefined ]
[ "complete match", undefined,     "MPD", undefined, undefined ]
[ "complete match", undefined, undefined,      "OK", undefined ]
[ "complete match", undefined, undefined, undefined,     "ACK" ]


Now you can either use the OR operator to get the case

mycase = result[1] || result[2] || result[3] || result[4];


Or just use a loop (be sure to only use non capturing groups for anything else but your cases)

for(var i = 1; i &lt; result.length; i++){
    mycase = mycase || result[i];
}