Apr 222012
Had to throw this together to handle some command line input for a little something I was toying with. It does the job I needed.
/**
* Splits a String into individual words or a quoted substring and puts the
* resulting String elements into a String array. I.e. a string like: This
* is a "sample string" would result in an array like
* {This, is, a, sample string}
* @param input A String to parse into an array
* @return A String array of the parsed input
*/
public String[] parse(String input) {
String[] result = null;
List list = new ArrayList<>();
Matcher matcher = Pattern.compile("([^\"]\\S*|\".+?\")\\s*").matcher(input);
while (matcher.find()) {
list.add(matcher.group(1));
}
result = new String[list.size()];
for(int i=0; i< list.size(); i++) {
result[i] = this.stripQuotes(list.get(i));
}
return result;
}
/**
* Removes double quotes from a String
* @param input A string that may contain double quotes to remove
* @return A String with no double quotes
*/
private String stripQuotes(String input) {
return input.replaceAll("\"", "");
}
louis vuitton fake purse…
Your article Split A String On A Space Delimiter, But Not On Substrings In Double Quotes » My Notes write very well, thank you share!…