正则表达式 - 将模式从php转换为Java

问题描述 投票:1回答:1

在PHP中我可以检查一个单词是否在这样的字符串中

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

例:

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

返回true


我尝试将其转换为Java:

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

同样的例子:

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

将返回false


我在这里错过了什么? :(

java regex
1个回答
5
投票

你必须使用Matcher并像这样调用find

Pattern pattern = Pattern.compile("(?i)\\b(" + word + ")\\b");
Matcher matcher = pattern.matcher(text);
System.out.println(matcher.find());// true if match false if not
© www.soinside.com 2019 - 2024. All rights reserved.