Lisa Cleaver
Lisa Cleaver

Reputation: 213

Regex - Convert pattern from php to Java

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? :(

Upvotes: 2

Views: 311

Answers (1)

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59986

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

Upvotes: 4

Related Questions