Skip to content

Instantly share code, notes, and snippets.

@wareya
Created November 15, 2015 09: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 wareya/3449314bbabf24464d1a to your computer and use it in GitHub Desktop.
Save wareya/3449314bbabf24464d1a to your computer and use it in GitHub Desktop.
// Septalicensed under the CC0, ISC, MIT, New-BSD, WTFPL, GNU All-Permissive, and Unlicense licenses.
// Code for splitting up a commandline-like string into a series of arguments, where \ escapes certain characters, including space, and "" escapes full arguments
std::vector<std::string> arglist;
std::string scraparg("");
bool escape = false;
bool encapsulate = false;
for(auto character : command)
{
if ( character == '\\' and escape == false ) // character is '\'
escape = true;
else
{
if ( escape )
{
switch ( character )
{
case 'n':
scraparg += '\n';
break;
case 't':
scraparg += '\t';
break;
case '\\':
scraparg += '\\';
break;
case '"':
scraparg += '\"';
break;
case ' ':
scraparg += ' ';
break;
default:
scraparg += '\\';
scraparg += character;
}
escape = false;
}
else
{
switch ( character )
{
case '"':
encapsulate = !encapsulate;
if (!encapsulate)
{
arglist.push_back(scraparg);
scraparg = "";
}
break;
case ' ':
if(encapsulate)
scraparg += ' ';
else
{
arglist.push_back(scraparg);
scraparg = "";
}
break;
default:
scraparg += character;
}
}
escape = false;
}
}
if(strcmp(scraparg.data(), "") != 0)
arglist.push_back(scraparg);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment