Skip to content

Instantly share code, notes, and snippets.

@dannyduc
Last active December 21, 2015 04:09
Show Gist options
  • Save dannyduc/6247382 to your computer and use it in GitHub Desktop.
Save dannyduc/6247382 to your computer and use it in GitHub Desktop.
Tokenize command line input with quoted characters
public class CommandLineTokenizer {
public static void main(String[] args) throws IOException, InterruptedException {
String cmdInput = "curl -X POST -H \"Content-Type:application/json\" -H \"Authorization: xxx\" -d '[{\"sampleId\":\"33\",\"activationCode\":\"Lab-act-code-xxx-zzz\"}]' https://developer.ingenuity.com/datastream/api/v1/activations/a9ab2c34-01b5-4473-864d-0d2f008ae090-5";
// tokenize with quote and single quote characters removed
List<String> matchTokens = new ArrayList<String>();
Pattern regex = Pattern.compile("[^\\s\"']+|\"([^\"]*)\"|'([^']*)'");
Matcher regexMatcher = regex.matcher(cmdInput);
while (regexMatcher.find()) {
if (regexMatcher.group(1) != null) {
// Add double-quoted string without the quotes
matchTokens.add(regexMatcher.group(1));
} else if (regexMatcher.group(2) != null) {
// Add single-quoted string without the quotes
matchTokens.add(regexMatcher.group(2));
} else {
// Add unquoted word
matchTokens.add(regexMatcher.group());
}
}
// tokenize and include quote and single quote characters
// List<String> matchTokens = new ArrayList<String>();
// Pattern regex = Pattern.compile("[^\\s\"']+|\"[^\"]*\"|'[^']*'");
// Matcher regexMatcher = regex.matcher(cmdInput);
// while (regexMatcher.find()) {
// matchTokens.add(regexMatcher.group());
// }
String[] cmds = matchTokens.toArray(new String[matchTokens.size()]);
Process process = Runtime.getRuntime().exec(cmds);
process.waitFor();
InputStream stream = process.getInputStream();
String content = IOUtils.toString(stream);
stream.close();
System.out.println(content);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment