如何在java中使用模式匹配器查找精确单词的匹配 我在这里分享了我的示例代码。在这里,我试图找到具有不同字符串的单词“引擎”。我使用单词边界来匹配字符串中的单词 如果以#engine开头,则与word匹配(示例)

如何在java中使用模式匹配器查找精确单词的匹配 我在这里分享了我的示例代码。在这里,我试图找到具有不同字符串的单词“引擎”。我使用单词边界来匹配字符串中的单词 如果以#engine开头,则与word匹配(示例),java,regex,pattern-matching,Java,Regex,Pattern Matching,它应该只与确切的单词匹配 private void checkMatch() { String source1 = "search engines has "; String source2 = "search engine exact word"; String source3 = "enginecheck"; String source4 = "has hashtag #engine"; String key = "engine"; Syst

它应该只与确切的单词匹配

private void checkMatch() {
    String source1 = "search engines has ";
    String source2 = "search engine exact word";
    String source3 = "enginecheck";
    String source4 = "has hashtag #engine";
    String key = "engine";

    System.out.println(isContain(source1, key));
    System.out.println(isContain(source2, key));
    System.out.println(isContain(source3, key));
    System.out.println(isContain(source4, key));

}

private boolean isContain(String source, String subItem) {
    String pattern = "\\b" + subItem + "\\b";
    Pattern p = Pattern.compile(pattern);
    Matcher m = p.matcher(source);
    return m.find();
}

**Expected output**
    false
    true
    false
    false

**actual output**
    false
    true
    false
    true

对于这种情况,必须使用regex或而不是word boundary
\\b
匹配单词字符和非单词字符(反之亦然)。因此您的正则表达式应该在
#engine
中找到匹配项,因为
#
是非单词字符

private boolean isContain(String source, String subItem) {
    String pattern = "(?m)(^|\\s)" + subItem + "(\\s|$)";
    Pattern p = Pattern.compile(pattern);
    Matcher m = p.matcher(source);
    return m.find();
}


String pattern=“(?如下更改您的模式

 String pattern = "\\s" + subItem + "\\b";

如果要查找包含空格或字符串开头/结尾的文本,可以使用类似
\s+
的空白模式拆分字符串,并检查是否有任何块与搜索文本相等

:

将regexp更改为

String pattern = "\\s"+subItem + "\\s";
我在用电话

\s是一个空白字符:[\t\n\x0B\f\r]

有关更多信息,请查看javadoc

此外,如果要支持以下字符串:

"has hashtag engine"
"engine"
您可以通过添加结束/起始行终止符(^和$)来改进它 通过使用此模式:

String pattern = "(^|\\s)"+subItem + "(\\s|$)";

对于所有的大小写,它都返回true@avinash非常感谢@avinash String pattern=“(?如果字符串包含一个完整的单词
引擎
,您只需要得到true还是false?并且:您只搜索文本吗?正则表达式搜索并不能真正搜索精确的字符串。只需删除
\b
s即可(java.util.Matcher随后将切换到字符串搜索),并检查边界是否为空白。
"has hashtag engine"
"engine"
String pattern = "(^|\\s)"+subItem + "(\\s|$)";