Split a quoted string with a delimiter

前端 未结 5 1513
清酒与你
清酒与你 2020-12-06 19:14

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 
<         


        
5条回答
  •  日久生厌
    2020-12-06 19:23

    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);     
    

提交回复
热议问题