I want to split a string with a delimiter white space. but it should handle quoted strings intelligently. E.g. for a string like
\"John Smith\" Ted Barry
<
Try this ugly bit of code.
String str = "hello my dear \"John Smith\" where is Ted Barry";
List list = Arrays.asList(str.split("\\s"));
List resultList = new ArrayList();
StringBuilder builder = new StringBuilder();
for(String s : list){
if(s.startsWith("\"")) {
builder.append(s.substring(1)).append(" ");
} else {
resultList.add((s.endsWith("\"")
? builder.append(s.substring(0, s.length() - 1))
: builder.append(s)).toString());
builder.delete(0, builder.length());
}
}
System.out.println(resultList);