我需要在 java 中用空格分隔单词,所以我使用了 .split
函数来实现这一点,如下所示
String keyword = "apple mango ";
String keywords [] = keyword .split(" ");
上面的代码工作正常,但唯一的问题是我的关键字有时会包含关键字,如 "jack fruit" 、"ice cream" 和双引号,如如下所示
String keyword = "apple mango \"jack fruit\" \"ice cream\"";
在这种情况下,我需要得到 4 个词,例如 apple、mango、jack fruit、ice cream在关键字数组中
谁能告诉我一些解决办法
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);
}
输出:
jack fruit
ice cream
apple
mango