Skip to content

Instantly share code, notes, and snippets.

@Ribesg
Created August 26, 2013 15:00
Show Gist options
  • Save Ribesg/6342375 to your computer and use it in GitHub Desktop.
Save Ribesg/6342375 to your computer and use it in GitHub Desktop.
/**
* Parses an original args array provided to a CommandExecutor to support quotes.
* If the parameter array is malformed, then this method returns the parameter array as-is.
*
* @param args The original args array. Ex: ['A', '"B', 'C', 'D"', 'E']
*
* @return The resulting args array, if valid. Ex: ['A', 'B C D', 'E']
*/
public static String[] parseArgumentsWithQuotes(String[] args) {
final List<String> resultList = new ArrayList<>();
boolean building = false;
StringBuilder builder = new StringBuilder();
for (String arg : args) {
if (arg.startsWith("\"")) {
if (building || arg.length() < 2) {
return args;
} else if (!arg.endsWith("\"")) {
builder.append(arg.substring(1));
} else if (args.length > 2) {
builder.append(arg.substring(1, arg.length() - 1));
} else {
return args;
}
} else if (building) {
builder.append(' ');
if (!arg.endsWith("\"")) {
builder.append(arg);
} else if (arg.length() < 2) {
return args;
} else {
builder.append(arg.substring(0, arg.length() - 1));
resultList.add(builder.toString());
builder = new StringBuilder();
}
} else {
resultList.add(arg);
}
}
return (String[]) resultList.toArray();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment