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

replaceAll is asymmetric for regex's '^' and '$'

    XMLWordPrintable

    Details

      Description

      ADDITIONAL SYSTEM INFORMATION :
      $ java -version
      java version "1.8.0_131"
      Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
      Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)

      A DESCRIPTION OF THE PROBLEM :
      The replaceAll behavior treats '^' and '$' inconsistently.

      '$' counts two:

      import java.util.regex.Pattern;
      class Test {
          public static void main(String[] args) {
              String input = "a\nb\nc\n";
              Pattern pattern = Pattern.compile("$");
              String result = pattern.matcher(input).replaceAll("XXX");
              System.out.println("a\nb\ncXXX\nXXX".equals(result)); // true
          }
      }

      and '^' counts one:

      import java.util.regex.Pattern;
      class Test {
          public static void main(String[] args) {
              String input = "a\nb\nc\n";
              Pattern pattern = Pattern.compile("^");
              String result = pattern.matcher(input).replaceAll("XXX");
              System.out.println("XXXa\nb\nc\n".equals(result)); // true
          }
      }

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      See description.

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      The start of line and end of line matcher should return the same number of results.

      In this case, I think '$' should return "a\nb\nc\nXXX".
      ACTUAL -
      See description.

      ---------- BEGIN SOURCE ----------
      See description.
      ---------- END SOURCE ----------

      CUSTOMER SUBMITTED WORKAROUND :
      None.

      FREQUENCY : always


        Attachments

          Issue Links

            Activity

              People

              Assignee:
              igerasim Ivan Gerasimov
              Reporter:
              webbuggrp Webbug Group
              Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

                Dates

                Created:
                Updated:
                Resolved: