Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split String by space separated [duplicate]

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

like image 564
Alex Man Avatar asked Mar 10 '23 12:03

Alex Man


2 Answers

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
like image 95
Tim Biegeleisen Avatar answered Mar 18 '23 06:03

Tim Biegeleisen


I'd do it with a regex and two capturing group, one for each pattern. I'm not aware of any other way.

    String keyword = "apple mango \"jack fruit\" \"ice cream\"";
    Pattern p = Pattern.compile("\"?(\\w+\\W+\\w+)\"|(\\w+)");      
    Matcher m = p.matcher(keyword);
    while (m.find()) {
        String word = m.group(1) == null ? m.group(2) : m.group(1);
        System.out.println(word);
    }
like image 41
mprivat Avatar answered Mar 18 '23 04:03

mprivat