java - 如何使用java中的模式匹配器找到精确单词的匹配

标签 java regex pattern-matching

  1. 我在这里分享了我的示例代码。在这里,我试图找到具有不同字符串的单词“engine”。我使用单词边界来匹配字符串中的单词。
  2. 如果单词以 #engine(example) 开头,则它与单词匹配。
  3. 它应该只与确切的单词匹配。

    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/

相关文章:

java - System.nanoTime() 是恒定时间操作吗?

java - java中的TCP服务器和TCP客户端

java - 如何处理未知实体引用?

javascript - 正则表达式:创建匹配模式时出现问题

kotlin - 为什么不能在 when 表达式中使用解构声明?

linux - Sed 替换失败,UTF-8 编码

java - 多个 java servlet 的 web.xml 中的通用初始化参数?

php - 正则表达式捕获查询字符串中的变量

regex - 如何删除一行中匹配项之间的所有文本?

scala - 没有案例类的模式匹配