0

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*"));
Shark44
  • 593
  • 1
  • 4
  • 11
  • What have you tried so far? Show some code examples. Also what is your question? Where are you stuck? – dunni Jun 29 '22 at 09:02
  • I think you can do it we regex. Check if the word is surrounded by spaces, dots, coma,... Or if it is in the start or the end of your text. – Y. Tarion Jun 29 '22 at 09:07
  • I've already tried with regex, but I am not sure of how to consider both the cases when the word is the starting one (no space before), or in the middle of the sentence – Shark44 Jun 29 '22 at 09:08

2 Answers2

1

You can use regexp to find words in text.

You should check this answer : Regex find word in the string

And you can try regex online with : https://regex101.com/

Y. Tarion
  • 433
  • 7
  • 17
1
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

Chicky
  • 185
  • 11