【问题标题】:Java RegEx negative lookbehindJava RegEx 负面回顾
【发布时间】:2013-08-03 15:50:49
【问题描述】:

我有以下 Java 代码:

Pattern pat = Pattern.compile("(?<!function )\\w+");
Matcher mat = pat.matcher("function example");
System.out.println(mat.find());

为什么mat.find() 返回真?我使用了否定的lookbehind,example前面是function。不应该被丢弃吗?

【问题讨论】:

    标签: java regex regex-lookarounds


    【解决方案1】:

    注意两点:

    • 您正在使用 find(),它也为 子字符串 匹配返回 true

    • 由于上述原因,“function”匹配,因为它前面没有“function”。
      整个字符串永远不会匹配,因为您的正则表达式没有 包括空格。

    改用带有负前瞻的Mathcher#matches()^$ 锚点:

    Pattern pat = Pattern.compile("^(?!function)[\\w\\s]+$"); // added \s for whitespaces
    Matcher mat = pat.matcher("function example");
    
    System.out.println(mat.find()); // false
    

    【讨论】:

      【解决方案2】:

      看看它匹配什么:

      public static void main(String[] args) throws Exception {
          Pattern pat = Pattern.compile("(?<!function )\\w+");
          Matcher mat = pat.matcher("function example");
          while (mat.find()) {
              System.out.println(mat.group());
          }
      }
      

      输出:

      function
      xample
      

      所以它首先找到function,它前面没有“function”。然后它会找到xample,它前面是function e,因此不是“function”。

      大概您希望模式匹配整个文本,而不仅仅是在文本中找到匹配

      您可以使用 Matcher.matches() 执行此操作,也可以更改模式以添加开始和结束锚点:

      ^(?<!function )\\w+$
      

      我更喜欢第二种方法,因为这意味着模式本身定义了它的匹配区域,而不是由它的用法定义的区域。然而,这只是一个偏好问题。

      【讨论】:

      【解决方案3】:

      您的字符串中包含匹配 \w+ 的单词“function”,并且前面没有“function”。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-09-07
        • 1970-01-01
        • 2016-05-19
        • 1970-01-01
        • 2022-11-10
        • 1970-01-01
        • 2014-12-20
        相关资源
        最近更新 更多