在Java中列出匹配词的所有下一个词。

huangapple go评论84阅读模式
英文:

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 + &quot;\\W+(\\w+)&quot;);
Matcher m = p.matcher(str);
List&lt;String&gt; words = new ArrayList&lt;&gt;();
while(m.find()){
  words.add(m.group(1));
}
return words;

Try it online.

huangapple
  • 本文由 发表于 2020年8月7日 20:42:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/63302117.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定