我有三个列表,我已将它们合并为一个列表
static List allLists = Stream.of(list1, list2, list3)
.flatMap(Collection::stream)
.collect(Collectors.toList());
我有没有空格的用户输入
String = "HelloIwanttobookanonlineseminaratyourcompany"
用户输入的String
中的所有单词都已经在allLists
中。我想遍历 allLists
并将空格插入到字符串中,找到每个单词。结果应该是:
String = "Hello I want to book an online seminar at your company"
有没有我想念的简单解决方案?
最佳答案
使用从 allLists
构建的(大量)look behind 的单行代码在每个单词前插入空格:
str = str.replaceAll("(?<=" + String.join("|", allLists) + ")", " ");
请注意,allLists
中的单词顺序很重要;如果您希望较长的单词优先,请先列出它们(推荐)。例如,如果“book”和“booking”都在您的列表中,请将 booking 放在 book 之前,否则您将在结果中得到“booking”。
关于java - 按列表中的单词拆分没有空格的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52132151/