1

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

kodu_
  • 39
  • 1
  • 6
  • Does this answer your question? [Find all occurrences of substring in string in Java](https://stackoverflow.com/questions/32788407/find-all-occurrences-of-substring-in-string-in-java) – jhamon Aug 07 '20 at 12:44

1 Answers1

1

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;

Try it online.

Kevin Cruijssen
  • 9,153
  • 9
  • 61
  • 135