Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8049849

Unclear behavior of regex $ character

    • Icon: Bug Bug
    • Resolution: Not an Issue
    • Icon: P4 P4
    • None
    • 8u5
    • core-libs

      A DESCRIPTION OF THE PROBLEM :
      The Pattern class's description of $ states: "By default, the regular expressions ^ and $ ignore line terminators and only match at the beginning and the end, respectively, of the entire input sequence." It says something similar further down in the description of the MULTILINE mode constant.

      The documentation is not consistent with what $ actually does. $ matches a terminating linefeed without multiline mode, as demonstrated by the following snippet:

          String linefeed = String.valueOf((char)10);
          System.out.println(java.util.regex.Pattern.compile("x$").matcher("x" + linefeed).find());

      The output is 'true'. The pattern matches even though the x is not immediately followed by the "end of the entire input sequence".

      However, I've noticed that if I call matches() instead of find(), it outputs 'false':

          System.out.println(java.util.regex.Pattern.compile("x$").matcher("x" + linefeed).matches());

      So now I'm confused. I'm not sure if the documentation or the implementation is wrong or if I'm just stupid.

      ((This report is (mostly) a duplicate of https://bugs.openjdk.java.net/browse/JDK-8043255 because the bug site apparently mangled the linefeed '\n' character in the first report, so no-one knew what I was talking about. The bug site doesn't let me comment on the earlier report to clarify, just like it didn't bother to let me see a preview of the report where it was mangling the bug, nor did it tell me the URL where the report ended up afterwards, nor did it tell me when the report was closed as bogus.))


      URL OF FAULTY DOCUMENTATION :
      http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html

            sherman Xueming Shen
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: