Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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*"));

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading