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

时间:2017-12-07 19:32:51

标签: java regex

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

我在这里缺少什么? :(

1 个答案:

答案 0 :(得分: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