java - 按空格分隔字符串

标签 java string parsing split word-spacing

<分区>

我需要在 java 中用空格分隔单词,所以我使用了 .split 函数来实现这一点,如下所示

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

上面的代码工作正常,但唯一的问题是我的关键字有时会包含关键字,如 "jack fruit""ice cream" 和双引号,如如下所示

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

在这种情况下,我需要得到 4 个词,例如 applema​​ngojack fruitice 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

关于java - 按空格分隔字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40912445/

相关文章:

java - 为什么读取 png 图像时会出现垃圾值

java - 将数组添加到 ArrayList

java - StringJoiner - 括号中的每一项

python - 将 python 中的字符串与文本文件进行比较

c - 最大限度地减少 sscanf 的内存消耗

java - 设置日期与声明?

java - Spring boot - Thymeleaf 与 JQuery?

java - 为什么 == 运算符在这里不起作用,但 equals 在 java 中起作用

c++ - 解析 C++ 以对代码进行一些更改

c - 从 Char* 数组中提取数字(C 字符串)