2

In php I can check if a word is in a String like that

$muster = "/\b($word)\b/i";
if(preg_match($muster, $text)) {
        return true;
}

Example:

$word = "test";
$text = "This is a :::test!!!";

Returns true


I tried converting this into Java:

if (Pattern.matches("(?i)\\b(" + word + ")\\b", text)) {
   return true;
}

The same example :

String word = "test";
String text = "This is a :::test!!!";

would return false


What am I missing here? :(

2
  • Pattern.matches("(?i).*\\b" + word + "\\b.*" as matches means match complete input in Java. Commented Dec 7, 2017 at 19:35
  • You can use indexOf to see if string contains a specific word. Commented Dec 7, 2017 at 19:36

1 Answer 1

4

You have to use Matcher and call find like this :

Pattern pattern = Pattern.compile("(?i)\\b(" + word + ")\\b");
Matcher matcher = pattern.matcher(text);
System.out.println(matcher.find());// true if match false if not
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.