Check whether sentence contains certain words

Viewed 54

I have a sentence like:

I`ve got a Pc

And a set of words:

Hello
world
Pc
dog

How can I check whether the sentence contains any of those words? In this example I would have a match with Pc.

Here is what I got so far:

public class SentenceWordExample {
    public static void main(String[] args) {
        String sentence = "I`ve got a Pc";
        String[] words = { "Hello", "world", "Pc", "dog" };

       // I know this does not work, but how to continue from here?
       if (line.contains(words) {
            System.out.println("Match!");
       } else {
            System.out.println("No match!");
        }
    }
}
2 Answers

I'd stream the array, and then check if the string contains any of its elements:

if (Arrays.stream(stringArray).anyMatch(s -> line.contains(s)) {
    // Do something...

I prefer using a regex approach here, with an alternation:

String line = "I`ve got a Pc";
String[] array = new String[2];
array[0] = "Example sentence";
array[1] = "Pc";
List<String> terms = Arrays.asList(array).stream()
    .map(x -> Pattern.quote(x)).collect(Collectors.toList());
String regex = ".*\\b(?:" + String.join("|", terms) + ")\\b.*";
if (line.matches(regex)) {
    System.out.println("MATCH");
}

The exact regex which the above snippet generates is:

.*\b(?:Example sentence|Pc)\b.*

That is, we form an alternation containing all keyword terms for which we want to search in the input string. Then, we use that regex with String#matches.

Related