0

I have to search a word in a Java String, but I don't know how to solve the following problem:

Ex: keyword: car

text: I want to take care of the cat.

The keyword appears in another word, but I don't want that to be detected. I want to detect only if the keyword isn't part of another word.

Ex keyword: car

text: I have a new car. (CORRECT)

I can't search for " car " (with spaces before and after), because it can appear as "car." in the text (the end of the sentence), so it would still not detect the correct situations

  • 3
    Have a look at [regular expressions](https://stackoverflow.com/questions/4736/learning-regular-expressions). There is a simple java regex solution for your problem. – maloomeister Nov 29 '21 at 15:30
  • Have a look at the [`Pattern`](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html) and [`Matcher`](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Matcher.html) classes from the `java.util.regex` package, which are a good place to start. – maloomeister Nov 29 '21 at 15:36
  • Possibly related: [Java match whole word in String](https://stackoverflow.com/q/38229378) – Pshemo Nov 29 '21 at 15:39

1 Answers1

1

A regular expression consisting of the input word between word boundaries \b needs to be compiled, then create a Matcher of the text, and use Matcher::find:

public static boolean containsWord(String text, String word) {
    return Patern.compile("\\b" + word + "\\b").matcher(text).find();
}
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42
  • 1
    Instead of `matches(".* … .*")` you might use `find("…")` – Holger Nov 29 '21 at 16:51
  • 3
    Yes, a few more letters to type for getting significantly better performance… – Holger Nov 29 '21 at 17:00
  • 1
    It’s easy to forget, but `text.matches(".*word.*")` has a different outcome than `Pattern.compile("word").matcher(text).find()` when `text` contains line breaks. Usually, the latter is matching the actual intention. I should have mentioned it first, but even I sometimes forget… – Holger Nov 29 '21 at 17:13