Last active
December 21, 2015 17:39
-
-
Save Ribesg/6342383 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 || arg.endsWith("\"") && arg.length() == 2) { | |
return args; | |
} else if (!arg.endsWith("\"")) { | |
building = true; | |
builder.append(arg.substring(1)); | |
} else { | |
builder.append(arg.substring(1, arg.length() - 1)); | |
} | |
} else if (building) { | |
if (!arg.endsWith("\"")) { | |
builder.append(' ' + arg); | |
} else if (arg.length() < 2) { | |
return args; | |
} else { | |
building = false; | |
resultList.add(builder.append(' ' + arg.substring(0, arg.length() - 1)).toString()); | |
builder = new StringBuilder(); | |
} | |
} else { | |
resultList.add(arg); | |
} | |
} | |
if (building) { | |
return args; | |
} | |
return (String[]) resultList.toArray(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment