< prev index next >

src/java.base/share/classes/java/util/regex/Pattern.java

Print this page
rev 12318 : [mq]: 8131034-Cleanup-in-j.u.regex.Pattern.quote

@@ -563,11 +563,11 @@
  * and outside of a character class.
  *
  * <p>
  * <b><a name="usc">Scripts</a></b> are specified either with the prefix {@code Is}, as in
  * {@code IsHiragana}, or by using  the {@code script} keyword (or its short
- * form {@code sc})as in {@code script=Hiragana} or {@code sc=Hiragana}.
+ * form {@code sc}) as in {@code script=Hiragana} or {@code sc=Hiragana}.
  * <p>
  * The script names supported by <code>Pattern</code> are the valid script names
  * accepted and defined by
  * {@link java.lang.Character.UnicodeScript#forName(String) UnicodeScript.forName}.
  *

@@ -1297,22 +1297,26 @@
     public static String quote(String s) {
         int slashEIndex = s.indexOf("\\E");
         if (slashEIndex == -1)
             return "\\Q" + s + "\\E";
 
-        StringBuilder sb = new StringBuilder(s.length() * 2);
+        int lenHint = s.length();
+        lenHint = (lenHint < Integer.MAX_VALUE - 8 - lenHint) ?
+                (lenHint << 1) : (Integer.MAX_VALUE - 8);
+
+        StringBuilder sb = new StringBuilder(lenHint);
         sb.append("\\Q");
-        slashEIndex = 0;
         int current = 0;
-        while ((slashEIndex = s.indexOf("\\E", current)) != -1) {
-            sb.append(s.substring(current, slashEIndex));
+        do {
+            sb.append(s, current, slashEIndex)
+                    .append("\\E\\\\E\\Q");
             current = slashEIndex + 2;
-            sb.append("\\E\\\\E\\Q");
-        }
-        sb.append(s.substring(current, s.length()));
-        sb.append("\\E");
-        return sb.toString();
+        } while ((slashEIndex = s.indexOf("\\E", current)) != -1);
+
+        return sb.append(s, current, s.length())
+                .append("\\E")
+                .toString();
     }
 
     /**
      * Recompile the Pattern instance from a stream.  The original pattern
      * string is read in and the object tree is recompiled from it.

@@ -1365,18 +1369,18 @@
             matchRoot = lastAccept;
         }
     }
 
     /**
-     * The pattern is converted to normalizedD form and then a pure group
+     * The pattern is converted to normalized form and then a pure group
      * is constructed to match canonical equivalences of the characters.
      */
     private void normalize() {
         boolean inCharClass = false;
         int lastCodePoint = -1;
 
-        // Convert pattern into normalizedD form
+        // Convert pattern into normalized form
         normalizedPattern = Normalizer.normalize(pattern, Normalizer.Form.NFD);
         patternLength = normalizedPattern.length();
 
         // Modify pattern to match canonical equivalences
         StringBuilder newPattern = new StringBuilder(patternLength);
< prev index next >