Last active
August 29, 2015 14:02
-
-
Save alex3305/40ebd0fab0e86457b576 to your computer and use it in GitHub Desktop.
Java 8 simple input validation with quotes
This file contains 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
/** | |
* Function that checks whether the command line input is valid. This | |
* method can handle input with spaces that are escaped inside | |
* quotation marks (either " or '). However this method will throw | |
* an Exception when either the input is empty or when the input | |
* is malformed. | |
* | |
* Malformed input occurs when there are an odd number of quotation | |
* marks in the input string, but only if there are more than one. | |
* | |
* @param input Input that should be validated. | |
* @return Validated input as an array. | |
* @throws NullPointerException When the input is empty. | |
* @throws IllegalArgumentException When there are an odd number | |
* of quotation marks. | |
*/ | |
private final String[] getInput(String input) throws NullPointerException, IllegalArgumentException { | |
if (input.isEmpty()) { | |
throw new NullPointerException("Input cannot be empty."); | |
} | |
if (input.chars().filter(c -> (c == ' ')).count() == 0) { | |
return new String[] { input }; | |
} | |
if (input.chars().filter(c -> (c == '"' || c == '\'')).count() % 2 == 1) { | |
throw new IllegalArgumentException("Malformed input, please check your syntax."); | |
} | |
int numberOfQuotes = 0; | |
String currentCommand = ""; | |
ArrayList<String> args = new ArrayList<>(); | |
for (char c : input.toCharArray()) { | |
if (c == '"' || c == '\'') { | |
numberOfQuotes++; | |
continue; | |
} | |
if (c == ' ' && numberOfQuotes % 2 == 0) { | |
args.add(currentCommand); | |
currentCommand = ""; | |
continue; | |
} | |
currentCommand += c; | |
} | |
if (!currentCommand.isEmpty()) { | |
args.add(currentCommand); | |
} | |
return args.toArray(new String[0]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment