Search code examples
javastring-matching

Java - Check if any of the words is contained in the text


I was trying to implement a method which checks whether a list of words is contained in a text. The problem is I cannot use the contains method because I just want the word to be detected (if the word is 'car' then with the string 'cars' the method should return false). In addition, the method should be case-sensitive.

EDIT:

String goodWord="word";
String review="This is a text containing the word.";
System.out.println(review.matches("\\w*"+goodWord+"\\w*"));

Solution

  • import java.util.regex.Pattern;
    
    public class Main {
        public static void main(String[] args) {
            String[] goodWords = { "good", "word" };
            String goodWordsUnionPatternStr = "(" + String.join("|", goodWords) + ")";
            Pattern strContainsGoodWordsPattern = Pattern.compile(".*\\b" + goodWordsUnionPatternStr + "\\b.*");
            String review = "This is a text containing the word.";
            System.out.println(strContainsGoodWordsPattern.matcher(review).matches());
        }
    }
    

    Explained:

    • \b is word boundary

    • Pattern.compile is preferred way due to performance