- 我在这里分享了我的示例代码。在这里,我试图找到具有不同字符串的单词“engine”。我使用单词边界来匹配字符串中的单词。
- 如果单词以 #engine(example) 开头,则它与单词匹配。
它应该只与确切的单词匹配。
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
最佳答案
对于这种情况,您必须使用正则表达式 OR 而不是单词边界。 \\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 = "(?<!\\S)" + subItem + "(?!\\S)";
关于java - 如何使用java中的模式匹配器找到精确单词的匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39524393/