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
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
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With