英文:
list all next word of matching word in java
问题
我已经使用下面的函数来打印下一个单词。
但它只打印第一个匹配的单词,如何打印所有单词?
字符串示例 = " 123 :G Hi all P: word I am new in java :G help me :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 0 0 0 0 0 0 0 0 0 0 :R 56 0 0 :G Please;
字符串匹配词= ":G";
public String nextWord(String str, String matchWord) {
Pattern p = Pattern.compile(matchWord + "\W+(\w+)");
Matcher m = p.matcher(str);
StringBuilder result = new StringBuilder();
while (m.find()) {
result.append(m.group(1)).append(" ");
}
return result.toString().trim();
}
当前输出:Hi
预期输出:Hi help Please
英文:
I have used below function to print next word.
But it prints only first matching word,How to print all words?
string example = " 123 :G Hi all P: word I am new in java :G help me :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 0 0 0 :R 56 0 0 :G Please;
string 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;
}
Current output: Hi
Expected Output: Hi help Please
答案1
得分: 1
你接近了。不仅仅是使用条件语句一次来检查 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;
英文:
You're close. Instead of only checking m.find()
once with a ternary if-statement, you should wrap it into a loop. Something like this:
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;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论