Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extract optional arguments / parameters from a string

Lets say I have the following string, which I may receive and require my program to act up on:

ACTION -F filter string -L location string -M message string

How can I reliably extract the ‘arguments’ from this string, all of which are optional to the user?

I spent a lot of time instead writing ACTION, filter, location, message and using .split(", ") to put the args to an array but found this too difficult to work reliably.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var content = req.body.Body.split(", ");    // [ Type, Filter, Location, Message]
var msgType = content[0].trim().toUpperCase();
            
if (msgType === 'INFO') {
    // return info based on remainder of parameters
    var filterGroup = content[1].trim();
    var destination = content[2].trim();

    var message = '';
                    
    // The message may be split further if it is written
    // with a ',' so concat them back together.
    if (content.length > 2) { // Optional message exists
                        
        // Message may be written in content[3] > content[n]
        // depending how many ', ' were written in the message.
        for (var i = 3; i < content.length; i++) {
                            
            message += content[i] + ", ";
                            
        }
    }

}

Is the -a argument format even the best way? Much googling returns information on extracting the arguments used to run a nodeJS program, but that isn’t applicable here, as the program is already running and the string not used at runtime. I’m at the design stage so have complete control over the format of the user input, but they’re sending a SMS with these commands so the simpler the better!

I’m writing in javascript and would appreciate your thoughts

>Solution :

You can use a regex to match the -X pattern and then use a loop to extract the strings between each pattern match.

The regex here is /(?<=\s)\-[A-Za-z](?=\s)/g, which looks for a dash followed by a letter with a white space character on either side.

const input = "ACTION -F filter string -L location string -M message string";
let regex = /(?<=\s)\-[A-Za-z](?=\s)/g;

let args = [];
while(match = regex.exec(input))
{
  args.push(match);
}

let solved = [];
for(let i = 0; i < args.length; i++)
{
  let cmd = args[i][0];
  let idx = args[i].index;
  let val;
  if(i + 1 == args.length)
    val = input.substr(idx + cmd.length + 1);
  else
    val = input.substring(idx + cmd.length + 1, args[i + 1].index - 1);
  solved.push({
    cmd: cmd,
    val: val
  });
}

console.log(solved);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading