0

I´m doing a project for school and I need my method to return true only to a certain word. This is what I have:

public boolean scanDescription (String keyword) {
    if (description.contains(keyword)) {
        return true;
    } else {
        return false;
    }

So for example, if the keyword is "disk", I need this method to return true only when a string contains the word "disk", but my problem is that it returns true when a string contains words like "diskette"

PS.: I have also tried to use .indexOf and it did not work

  • equalsIgnoreCase() works if it is a case insensitive match and equals() for a case sensitive search – Sara Apr 29 '20 at 03:07
  • This will show you the hints for your answer https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java – Sarangan Apr 29 '20 at 03:11
  • Does this answer your question? [Find a complete word in a string java](https://stackoverflow.com/questions/2765482/find-a-complete-word-in-a-string-java) – Rahal Kanishka Apr 29 '20 at 03:15

1 Answers1

4

You should use the word boundary.

public boolean scanDescription(String keyword) {
     Pattern pattern = Pattern.compile("\\b"+keyword+"\\b");
     return pattern.matcher(description).find();
}
Amir MB
  • 3,233
  • 2
  • 10
  • 16