我已经使用了以下功能来打印下一个单词。
但是它只打印第一个匹配的单词,如何打印所有单词?
字符串示例=“ 123:G大家好P:单词我是Java的新手:G帮助我:N abc 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0:R 56 0 0:G 字符串matchWord =“”:G“;
public String nextWord(String str, String matchWord) {
Pattern p = Pattern.compile(matchWord + "\\W+(\\w+)");
Matcher m = p.matcher(str);
return m.find() ? m.group(1) : null;
}
电流输出:高 预期输出:嗨,请帮忙
答案 0 :(得分:1)
您已经关闭。您应该将其包装到循环中,而不是仅使用三元if语句检查一次m.find()
。像这样:
Pattern p = Pattern.compile(matchWord + "\\W+(\\w+)");
Matcher m = p.matcher(str);
List<String> words = new ArrayList<>();
while(m.find()){
words.add(m.group(1));
}
return words;