Skip to content

Instantly share code, notes, and snippets.

@fracek
Created June 13, 2012 13:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fracek/2923969 to your computer and use it in GitHub Desktop.
Save fracek/2923969 to your computer and use it in GitHub Desktop.
parse command
#!/usr/bin/env node
/*
* Given a string return a map in the form { cmd: 'args', cmd2: 'args' }
*/
function parseCommand(s) {
m = {}
state = 0;
currentcmd = '';
currentargs = '';
for (i = 0; i < s.length; i++) {
c = s[i];
//console.log(c, ' ', state);
switch (state) {
case 0:
if (c != ' ') {
state = 1;
currentcmd += c;
}
break;
case 1:
if (c == ' ') {
state = 2;
} else {
currentcmd += c;
}
break;
case 2:
if (c != ' ') {
state = 3;
currentargs += c;
}
break;
case 3:
if (c == '\n') {
state = 0;
m[currentcmd] = currentargs;
currentcmd = '';
currentargs = '';
} else {
currentargs += c;
}
break;
}
}
m[currentcmd] = currentargs;
return m;
}
var cmds = ['mono program.exe arg1 arg2',
' mono program.exe arg1 arg2',
'cmd1 arg1 arg2 arg3\n cmd2 arg11 arg12 etc '];
cmds.forEach(function(c) {
console.log(c, parseCommand(c));
});
/*
* Requires node.js
* $ node parse.js
* mono program.exe arg1 arg2 { mono: 'program.exe arg1 arg2' }
* mono program.exe arg1 arg2 { mono: 'program.exe arg1 arg2' }
* cmd1 arg1 arg2 arg3
* cmd2 arg11 arg12 etc { cmd1: 'arg1 arg2 arg3', cmd2: 'arg11 arg12 etc ' }
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment