Detect If a String Contains Multiple Keywords in Java

On this page, you will learn how to detect multiple words inside of a string in Java.

Firstly, let's suppose that we have a string like this, String inputString = "Summer is Good". And then, we are ready to check whether the inputString contains the "Summer" and "Good" words.

Now, let's put our keywords into an array, String[] words = {"Summer", "Good"}. Please note that the order of the words isn't important, but the matches should be case-sensitive.

1. How to with String.contains()

The first way to detect if a String contains multiple keywords in Java is to use the String.contains() method. Let's loop over the keywords array and check the occurrence of each item inside of the inputString. The method contains(), which will return true if the inputString contains the given item.

public static boolean containsWords(String inputString, String[] items) {
    boolean found = true;
    for (String item : items) {
        if (!inputString.contains(item)) {
            found = false;
            break;
        }
    }
    return found;
}

2. How to with String.indexOf()

To achieve our goal, we can also use the String.contains() method. To be specific, we can check the indices of the keywords by using the String.indexOf() method. For that, we need a method accepting the inputString and the list of the keywords.

public static boolean containsWordsIndexOf(String inputString, String[] words) {
    boolean found = true;
    for (String word : words) {
        if (inputString.indexOf(word) == -1) {
            found = false;
            break;
        }
    }
    return found;
}

3. How to with Regular Expressions

We can use a regular expression to match our words, which means we'll use the Pattern class. First, let's define the string expression. As we need to match two keywords, we'll build our regex rule with two lookaheads.

Pattern pattern = Pattern.compile("(?=.*Summer)(?=.*Good)");}

In the general case:

StringBuilder regexp = new StringBuilder();
for (String word : words) {
    regexp.append("(?=.*").append(word).append(")");

And then, we can use the matcher() method to find() the occurrences.

public static boolean containsWordsPatternMatch(String inputString, String[] words) {

    StringBuilder regexp = new StringBuilder();
    for (String word : words) {
        regexp.append("(?=.*").append(word).append(")");
    }

    Pattern pattern = Pattern.compile(regexp.toString());

    return pattern.matcher(inputString).find();
}


Leave a reply



Submit