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

Java Matcher.find $ matches newline in single line mode

    XMLWordPrintable

    Details

      Description

      A DESCRIPTION OF THE PROBLEM :
      I'm trying the following Pattern:

      Pattern p = Pattern.compile("^(\\d+)$");

      Strangely, IMHO:

      p.matcher("123\n").find() == true;
      p.matcher("123\n").lookingAt() == true; // also weird
      p.matcher("123\n\n").find() == false; // ok
      p.matcher("123\na").find() == false; // also ok
      p.matcher("123\n").matches() == false; // ok to me

      Quoting the documentation for the "multiline flag" from the Javadocs:

      "Enables multiline mode. In multiline mode the expressions ^ and $ match just after or just before, respectively, a line terminator or the end of the input sequence. By default these expressions only match at the beginning and the end of the entire input sequence."

      Well, to me '\n' (i.e the new line character) is not the end of the input sequence, so '$' should only match it in multiline mode.

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      Just compile and execute the sample unit test I provided.

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      Look at the source code. I would expect all assertions to pass.
      ACTUAL -
      Look at the source code. The two first assertions fail.

      ---------- BEGIN SOURCE ----------
      import org.junit.Test;
      import java.util.regex.Pattern;
      import static org.junit.Assert.assertFalse;

      public class BugTest
      {
          @Test
          public void testMe()
          {
              Pattern p = Pattern.compile("^(\\d+)$");

              assertFalse(p.matcher("123\n").find()); // this fails, but should not
              assertFalse(p.matcher("123\n").lookingAt()); // also fails
              assertFalse(p.matcher("123\n\n").find()); // ok
              assertFalse(p.matcher("123\na").find()); // also ok
              assertFalse(p.matcher("123\n").matches()); // ok to me
          }
      }

      ---------- END SOURCE ----------

      FREQUENCY : always


        Attachments

          Issue Links

            Activity

              People

              Assignee:
              igraves Ian Graves
              Reporter:
              webbuggrp Webbug Group
              Votes:
              0 Vote for this issue
              Watchers:
              3 Start watching this issue

                Dates

                Created:
                Updated:
                Resolved: