Although the regex approach is certainly a valid method, itβs easier for me to think through when you divide the words into spaces. This can be done using the String split method.
public List<String> doIt(final String inputString, final String term) { final List<String> output = new ArrayList<String>(); final String[] parts = input.split("\\s+"); for(final String part : parts) { if(part.indexOf(term) > 0) { output.add(part); } } return output; }
Of course, it costs nothing that it will effectively do two passes through your input string. The first pass is to find characters that are space separators, and the second pass looks through each separated word for your substring.
If one pass is required, the regex path is better.
source share