Search code examples
javastringparsingsplitword-spacing

split String by space separated


I need to split words by space separated in java, so I have used .split function in-order to achieve that like as shown below

String keyword = "apple mango ";
String keywords [] = keyword .split(" ");

The above code is working fine but the only is that I sometimes my keyword will contain keyword like "jack fruit" , "ice cream" with double quotes like as shown below

String keyword = "apple mango \"jack fruit\" \"ice cream\"";

In this case I need to get 4 words like apple, mango, jack fruit, ice cream in keywords array

Can anyone please tell me some solution for this


Solution

  • List<String> parts = new ArrayList<>();
    String keyword = "apple mango \"jack fruit\" \"ice cream\"";
    
    // first use a matcher to grab the quoted terms
    Pattern p = Pattern.compile("\"(.*?)\"");      
    Matcher m = p.matcher(keyword);
    while (m.find()) {
        parts.add(m.group(1));
    }
    
    // then remove all quoted terms (quotes included)
    keyword = keyword.replaceAll("\".*?\"", "")
                     .trim();
    
    // finally split the remaining keywords on whitespace
    if (keyword.replaceAll("\\s", "").length() > 0) {
        Collections.addAll(parts, keyword.split("\\s+"));
    }
    
    for (String part : parts) {
        System.out.println(part);
    }
    

    Output:

    jack fruit
    ice cream
    apple
    mango