1 /*
   2  * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.util.regex;
  27 
  28 import java.text.Normalizer;
  29 import java.util.Locale;
  30 import java.util.Iterator;
  31 import java.util.Map;
  32 import java.util.ArrayList;
  33 import java.util.HashMap;
  34 import java.util.Arrays;
  35 import java.util.NoSuchElementException;
  36 import java.util.Spliterator;
  37 import java.util.Spliterators;
  38 import java.util.function.Predicate;
  39 import java.util.stream.Stream;
  40 import java.util.stream.StreamSupport;
  41 
  42 
  43 /**
  44  * A compiled representation of a regular expression.
  45  *
  46  * <p> A regular expression, specified as a string, must first be compiled into
  47  * an instance of this class.  The resulting pattern can then be used to create
  48  * a {@link Matcher} object that can match arbitrary {@linkplain
  49  * java.lang.CharSequence character sequences} against the regular
  50  * expression.  All of the state involved in performing a match resides in the
  51  * matcher, so many matchers can share the same pattern.
  52  *
  53  * <p> A typical invocation sequence is thus
  54  *
  55  * <blockquote><pre>
  56  * Pattern p = Pattern.{@link #compile compile}("a*b");
  57  * Matcher m = p.{@link #matcher matcher}("aaaaab");
  58  * boolean b = m.{@link Matcher#matches matches}();</pre></blockquote>
  59  *
  60  * <p> A {@link #matches matches} method is defined by this class as a
  61  * convenience for when a regular expression is used just once.  This method
  62  * compiles an expression and matches an input sequence against it in a single
  63  * invocation.  The statement
  64  *
  65  * <blockquote><pre>
  66  * boolean b = Pattern.matches("a*b", "aaaaab");</pre></blockquote>
  67  *
  68  * is equivalent to the three statements above, though for repeated matches it
  69  * is less efficient since it does not allow the compiled pattern to be reused.
  70  *
  71  * <p> Instances of this class are immutable and are safe for use by multiple
  72  * concurrent threads.  Instances of the {@link Matcher} class are not safe for
  73  * such use.
  74  *
  75  *
  76  * <h3><a name="sum">Summary of regular-expression constructs</a></h3>
  77  *
  78  * <table border="0" cellpadding="1" cellspacing="0"
  79  *  summary="Regular expression constructs, and what they match">
  80  *
  81  * <tr align="left">
  82  * <th align="left" id="construct">Construct</th>
  83  * <th align="left" id="matches">Matches</th>
  84  * </tr>
  85  *
  86  * <tr><th>&nbsp;</th></tr>
  87  * <tr align="left"><th colspan="2" id="characters">Characters</th></tr>
  88  *
  89  * <tr><td valign="top" headers="construct characters"><i>x</i></td>
  90  *     <td headers="matches">The character <i>x</i></td></tr>
  91  * <tr><td valign="top" headers="construct characters"><tt>\\</tt></td>
  92  *     <td headers="matches">The backslash character</td></tr>
  93  * <tr><td valign="top" headers="construct characters"><tt>\0</tt><i>n</i></td>
  94  *     <td headers="matches">The character with octal value <tt>0</tt><i>n</i>
  95  *         (0&nbsp;<tt>&lt;=</tt>&nbsp;<i>n</i>&nbsp;<tt>&lt;=</tt>&nbsp;7)</td></tr>
  96  * <tr><td valign="top" headers="construct characters"><tt>\0</tt><i>nn</i></td>
  97  *     <td headers="matches">The character with octal value <tt>0</tt><i>nn</i>
  98  *         (0&nbsp;<tt>&lt;=</tt>&nbsp;<i>n</i>&nbsp;<tt>&lt;=</tt>&nbsp;7)</td></tr>
  99  * <tr><td valign="top" headers="construct characters"><tt>\0</tt><i>mnn</i></td>
 100  *     <td headers="matches">The character with octal value <tt>0</tt><i>mnn</i>
 101  *         (0&nbsp;<tt>&lt;=</tt>&nbsp;<i>m</i>&nbsp;<tt>&lt;=</tt>&nbsp;3,
 102  *         0&nbsp;<tt>&lt;=</tt>&nbsp;<i>n</i>&nbsp;<tt>&lt;=</tt>&nbsp;7)</td></tr>
 103  * <tr><td valign="top" headers="construct characters"><tt>\x</tt><i>hh</i></td>
 104  *     <td headers="matches">The character with hexadecimal&nbsp;value&nbsp;<tt>0x</tt><i>hh</i></td></tr>
 105  * <tr><td valign="top" headers="construct characters"><tt>&#92;u</tt><i>hhhh</i></td>
 106  *     <td headers="matches">The character with hexadecimal&nbsp;value&nbsp;<tt>0x</tt><i>hhhh</i></td></tr>
 107  * <tr><td valign="top" headers="construct characters"><tt>&#92;x</tt><i>{h...h}</i></td>
 108  *     <td headers="matches">The character with hexadecimal&nbsp;value&nbsp;<tt>0x</tt><i>h...h</i>
 109  *         ({@link java.lang.Character#MIN_CODE_POINT Character.MIN_CODE_POINT}
 110  *         &nbsp;&lt;=&nbsp;<tt>0x</tt><i>h...h</i>&nbsp;&lt;=&nbsp;
 111  *          {@link java.lang.Character#MAX_CODE_POINT Character.MAX_CODE_POINT})</td></tr>
 112  * <tr><td valign="top" headers="matches"><tt>\t</tt></td>
 113  *     <td headers="matches">The tab character (<tt>'&#92;u0009'</tt>)</td></tr>
 114  * <tr><td valign="top" headers="construct characters"><tt>\n</tt></td>
 115  *     <td headers="matches">The newline (line feed) character (<tt>'&#92;u000A'</tt>)</td></tr>
 116  * <tr><td valign="top" headers="construct characters"><tt>\r</tt></td>
 117  *     <td headers="matches">The carriage-return character (<tt>'&#92;u000D'</tt>)</td></tr>
 118  * <tr><td valign="top" headers="construct characters"><tt>\f</tt></td>
 119  *     <td headers="matches">The form-feed character (<tt>'&#92;u000C'</tt>)</td></tr>
 120  * <tr><td valign="top" headers="construct characters"><tt>\a</tt></td>
 121  *     <td headers="matches">The alert (bell) character (<tt>'&#92;u0007'</tt>)</td></tr>
 122  * <tr><td valign="top" headers="construct characters"><tt>\e</tt></td>
 123  *     <td headers="matches">The escape character (<tt>'&#92;u001B'</tt>)</td></tr>
 124  * <tr><td valign="top" headers="construct characters"><tt>\c</tt><i>x</i></td>
 125  *     <td headers="matches">The control character corresponding to <i>x</i></td></tr>
 126  *
 127  * <tr><th>&nbsp;</th></tr>
 128  * <tr align="left"><th colspan="2" id="classes">Character classes</th></tr>
 129  *
 130  * <tr><td valign="top" headers="construct classes">{@code [abc]}</td>
 131  *     <td headers="matches">{@code a}, {@code b}, or {@code c} (simple class)</td></tr>
 132  * <tr><td valign="top" headers="construct classes">{@code [^abc]}</td>
 133  *     <td headers="matches">Any character except {@code a}, {@code b}, or {@code c} (negation)</td></tr>
 134  * <tr><td valign="top" headers="construct classes">{@code [a-zA-Z]}</td>
 135  *     <td headers="matches">{@code a} through {@code z}
 136  *         or {@code A} through {@code Z}, inclusive (range)</td></tr>
 137  * <tr><td valign="top" headers="construct classes">{@code [a-d[m-p]]}</td>
 138  *     <td headers="matches">{@code a} through {@code d},
 139  *      or {@code m} through {@code p}: {@code [a-dm-p]} (union)</td></tr>
 140  * <tr><td valign="top" headers="construct classes">{@code [a-z&&[def]]}</td>
 141  *     <td headers="matches">{@code d}, {@code e}, or {@code f} (intersection)</tr>
 142  * <tr><td valign="top" headers="construct classes">{@code [a-z&&[^bc]]}</td>
 143  *     <td headers="matches">{@code a} through {@code z},
 144  *         except for {@code b} and {@code c}: {@code [ad-z]} (subtraction)</td></tr>
 145  * <tr><td valign="top" headers="construct classes">{@code [a-z&&[^m-p]]}</td>
 146  *     <td headers="matches">{@code a} through {@code z},
 147  *          and not {@code m} through {@code p}: {@code [a-lq-z]}(subtraction)</td></tr>
 148  * <tr><th>&nbsp;</th></tr>
 149  *
 150  * <tr align="left"><th colspan="2" id="predef">Predefined character classes</th></tr>
 151  *
 152  * <tr><td valign="top" headers="construct predef"><tt>.</tt></td>
 153  *     <td headers="matches">Any character (may or may not match <a href="#lt">line terminators</a>)</td></tr>
 154  * <tr><td valign="top" headers="construct predef"><tt>\d</tt></td>
 155  *     <td headers="matches">A digit: <tt>[0-9]</tt></td></tr>
 156  * <tr><td valign="top" headers="construct predef"><tt>\D</tt></td>
 157  *     <td headers="matches">A non-digit: <tt>[^0-9]</tt></td></tr>
 158  * <tr><td valign="top" headers="construct predef"><tt>\h</tt></td>
 159  *     <td headers="matches">A horizontal whitespace character:
 160  *     <tt>[ \t\xA0&#92;u1680&#92;u180e&#92;u2000-&#92;u200a&#92;u202f&#92;u205f&#92;u3000]</tt></td></tr>
 161  * <tr><td valign="top" headers="construct predef"><tt>\H</tt></td>
 162  *     <td headers="matches">A non-horizontal whitespace character: <tt>[^\h]</tt></td></tr>
 163  * <tr><td valign="top" headers="construct predef"><tt>\s</tt></td>
 164  *     <td headers="matches">A whitespace character: <tt>[ \t\n\x0B\f\r]</tt></td></tr>
 165  * <tr><td valign="top" headers="construct predef"><tt>\S</tt></td>
 166  *     <td headers="matches">A non-whitespace character: <tt>[^\s]</tt></td></tr>
 167  * <tr><td valign="top" headers="construct predef"><tt>\v</tt></td>
 168  *     <td headers="matches">A vertical whitespace character: <tt>[\n\x0B\f\r\x85&#92;u2028&#92;u2029]</tt>
 169  *     </td></tr>
 170  * <tr><td valign="top" headers="construct predef"><tt>\V</tt></td>
 171  *     <td headers="matches">A non-vertical whitespace character: <tt>[^\v]</tt></td></tr>
 172  * <tr><td valign="top" headers="construct predef"><tt>\w</tt></td>
 173  *     <td headers="matches">A word character: <tt>[a-zA-Z_0-9]</tt></td></tr>
 174  * <tr><td valign="top" headers="construct predef"><tt>\W</tt></td>
 175  *     <td headers="matches">A non-word character: <tt>[^\w]</tt></td></tr>
 176  * <tr><th>&nbsp;</th></tr>
 177  * <tr align="left"><th colspan="2" id="posix"><b>POSIX character classes (US-ASCII only)</b></th></tr>
 178  *
 179  * <tr><td valign="top" headers="construct posix">{@code \p{Lower}}</td>
 180  *     <td headers="matches">A lower-case alphabetic character: {@code [a-z]}</td></tr>
 181  * <tr><td valign="top" headers="construct posix">{@code \p{Upper}}</td>
 182  *     <td headers="matches">An upper-case alphabetic character:{@code [A-Z]}</td></tr>
 183  * <tr><td valign="top" headers="construct posix">{@code \p{ASCII}}</td>
 184  *     <td headers="matches">All ASCII:{@code [\x00-\x7F]}</td></tr>
 185  * <tr><td valign="top" headers="construct posix">{@code \p{Alpha}}</td>
 186  *     <td headers="matches">An alphabetic character:{@code [\p{Lower}\p{Upper}]}</td></tr>
 187  * <tr><td valign="top" headers="construct posix">{@code \p{Digit}}</td>
 188  *     <td headers="matches">A decimal digit: {@code [0-9]}</td></tr>
 189  * <tr><td valign="top" headers="construct posix">{@code \p{Alnum}}</td>
 190  *     <td headers="matches">An alphanumeric character:{@code [\p{Alpha}\p{Digit}]}</td></tr>
 191  * <tr><td valign="top" headers="construct posix">{@code \p{Punct}}</td>
 192  *     <td headers="matches">Punctuation: One of {@code !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~}</td></tr>
 193  *     <!-- {@code [\!"#\$%&'\(\)\*\+,\-\./:;\<=\>\?@\[\\\]\^_`\{\|\}~]}
 194  *          {@code [\X21-\X2F\X31-\X40\X5B-\X60\X7B-\X7E]} -->
 195  * <tr><td valign="top" headers="construct posix">{@code \p{Graph}}</td>
 196  *     <td headers="matches">A visible character: {@code [\p{Alnum}\p{Punct}]}</td></tr>
 197  * <tr><td valign="top" headers="construct posix">{@code \p{Print}}</td>
 198  *     <td headers="matches">A printable character: {@code [\p{Graph}\x20]}</td></tr>
 199  * <tr><td valign="top" headers="construct posix">{@code \p{Blank}}</td>
 200  *     <td headers="matches">A space or a tab: {@code [ \t]}</td></tr>
 201  * <tr><td valign="top" headers="construct posix">{@code \p{Cntrl}}</td>
 202  *     <td headers="matches">A control character: {@code [\x00-\x1F\x7F]}</td></tr>
 203  * <tr><td valign="top" headers="construct posix">{@code \p{XDigit}}</td>
 204  *     <td headers="matches">A hexadecimal digit: {@code [0-9a-fA-F]}</td></tr>
 205  * <tr><td valign="top" headers="construct posix">{@code \p{Space}}</td>
 206  *     <td headers="matches">A whitespace character: {@code [ \t\n\x0B\f\r]}</td></tr>
 207  *
 208  * <tr><th>&nbsp;</th></tr>
 209  * <tr align="left"><th colspan="2">java.lang.Character classes (simple <a href="#jcc">java character type</a>)</th></tr>
 210  *
 211  * <tr><td valign="top"><tt>\p{javaLowerCase}</tt></td>
 212  *     <td>Equivalent to java.lang.Character.isLowerCase()</td></tr>
 213  * <tr><td valign="top"><tt>\p{javaUpperCase}</tt></td>
 214  *     <td>Equivalent to java.lang.Character.isUpperCase()</td></tr>
 215  * <tr><td valign="top"><tt>\p{javaWhitespace}</tt></td>
 216  *     <td>Equivalent to java.lang.Character.isWhitespace()</td></tr>
 217  * <tr><td valign="top"><tt>\p{javaMirrored}</tt></td>
 218  *     <td>Equivalent to java.lang.Character.isMirrored()</td></tr>
 219  *
 220  * <tr><th>&nbsp;</th></tr>
 221  * <tr align="left"><th colspan="2" id="unicode">Classes for Unicode scripts, blocks, categories and binary properties</th></tr>
 222  * <tr><td valign="top" headers="construct unicode">{@code \p{IsLatin}}</td>
 223  *     <td headers="matches">A Latin&nbsp;script character (<a href="#usc">script</a>)</td></tr>
 224  * <tr><td valign="top" headers="construct unicode">{@code \p{InGreek}}</td>
 225  *     <td headers="matches">A character in the Greek&nbsp;block (<a href="#ubc">block</a>)</td></tr>
 226  * <tr><td valign="top" headers="construct unicode">{@code \p{Lu}}</td>
 227  *     <td headers="matches">An uppercase letter (<a href="#ucc">category</a>)</td></tr>
 228  * <tr><td valign="top" headers="construct unicode">{@code \p{IsAlphabetic}}</td>
 229  *     <td headers="matches">An alphabetic character (<a href="#ubpc">binary property</a>)</td></tr>
 230  * <tr><td valign="top" headers="construct unicode">{@code \p{Sc}}</td>
 231  *     <td headers="matches">A currency symbol</td></tr>
 232  * <tr><td valign="top" headers="construct unicode">{@code \P{InGreek}}</td>
 233  *     <td headers="matches">Any character except one in the Greek block (negation)</td></tr>
 234  * <tr><td valign="top" headers="construct unicode">{@code [\p{L}&&[^\p{Lu}]]}</td>
 235  *     <td headers="matches">Any letter except an uppercase letter (subtraction)</td></tr>
 236  *
 237  * <tr><th>&nbsp;</th></tr>
 238  * <tr align="left"><th colspan="2" id="bounds">Boundary matchers</th></tr>
 239  *
 240  * <tr><td valign="top" headers="construct bounds"><tt>^</tt></td>
 241  *     <td headers="matches">The beginning of a line</td></tr>
 242  * <tr><td valign="top" headers="construct bounds"><tt>$</tt></td>
 243  *     <td headers="matches">The end of a line</td></tr>
 244  * <tr><td valign="top" headers="construct bounds"><tt>\b</tt></td>
 245  *     <td headers="matches">A word boundary</td></tr>
 246  * <tr><td valign="top" headers="construct bounds"><tt>\B</tt></td>
 247  *     <td headers="matches">A non-word boundary</td></tr>
 248  * <tr><td valign="top" headers="construct bounds"><tt>\A</tt></td>
 249  *     <td headers="matches">The beginning of the input</td></tr>
 250  * <tr><td valign="top" headers="construct bounds"><tt>\G</tt></td>
 251  *     <td headers="matches">The end of the previous match</td></tr>
 252  * <tr><td valign="top" headers="construct bounds"><tt>\Z</tt></td>
 253  *     <td headers="matches">The end of the input but for the final
 254  *         <a href="#lt">terminator</a>, if&nbsp;any</td></tr>
 255  * <tr><td valign="top" headers="construct bounds"><tt>\z</tt></td>
 256  *     <td headers="matches">The end of the input</td></tr>
 257  *
 258  * <tr><th>&nbsp;</th></tr>
 259  * <tr align="left"><th colspan="2" id="lineending">Linebreak matcher</th></tr>
 260  * <tr><td valign="top" headers="construct lineending"><tt>\R</tt></td>
 261  *     <td headers="matches">Any Unicode linebreak sequence, is equivalent to
 262  *     <tt>&#92;u000D&#92;u000A|[&#92;u000A&#92;u000B&#92;u000C&#92;u000D&#92;u0085&#92;u2028&#92;u2029]
 263  *     </tt></td></tr>
 264  *
 265  * <tr><th>&nbsp;</th></tr>
 266  * <tr align="left"><th colspan="2" id="greedy">Greedy quantifiers</th></tr>
 267  *
 268  * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>?</tt></td>
 269  *     <td headers="matches"><i>X</i>, once or not at all</td></tr>
 270  * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>*</tt></td>
 271  *     <td headers="matches"><i>X</i>, zero or more times</td></tr>
 272  * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>+</tt></td>
 273  *     <td headers="matches"><i>X</i>, one or more times</td></tr>
 274  * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>{</tt><i>n</i><tt>}</tt></td>
 275  *     <td headers="matches"><i>X</i>, exactly <i>n</i> times</td></tr>
 276  * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>{</tt><i>n</i><tt>,}</tt></td>
 277  *     <td headers="matches"><i>X</i>, at least <i>n</i> times</td></tr>
 278  * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>{</tt><i>n</i><tt>,</tt><i>m</i><tt>}</tt></td>
 279  *     <td headers="matches"><i>X</i>, at least <i>n</i> but not more than <i>m</i> times</td></tr>
 280  *
 281  * <tr><th>&nbsp;</th></tr>
 282  * <tr align="left"><th colspan="2" id="reluc">Reluctant quantifiers</th></tr>
 283  *
 284  * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>??</tt></td>
 285  *     <td headers="matches"><i>X</i>, once or not at all</td></tr>
 286  * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>*?</tt></td>
 287  *     <td headers="matches"><i>X</i>, zero or more times</td></tr>
 288  * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>+?</tt></td>
 289  *     <td headers="matches"><i>X</i>, one or more times</td></tr>
 290  * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>{</tt><i>n</i><tt>}?</tt></td>
 291  *     <td headers="matches"><i>X</i>, exactly <i>n</i> times</td></tr>
 292  * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>{</tt><i>n</i><tt>,}?</tt></td>
 293  *     <td headers="matches"><i>X</i>, at least <i>n</i> times</td></tr>
 294  * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>{</tt><i>n</i><tt>,</tt><i>m</i><tt>}?</tt></td>
 295  *     <td headers="matches"><i>X</i>, at least <i>n</i> but not more than <i>m</i> times</td></tr>
 296  *
 297  * <tr><th>&nbsp;</th></tr>
 298  * <tr align="left"><th colspan="2" id="poss">Possessive quantifiers</th></tr>
 299  *
 300  * <tr><td valign="top" headers="construct poss"><i>X</i><tt>?+</tt></td>
 301  *     <td headers="matches"><i>X</i>, once or not at all</td></tr>
 302  * <tr><td valign="top" headers="construct poss"><i>X</i><tt>*+</tt></td>
 303  *     <td headers="matches"><i>X</i>, zero or more times</td></tr>
 304  * <tr><td valign="top" headers="construct poss"><i>X</i><tt>++</tt></td>
 305  *     <td headers="matches"><i>X</i>, one or more times</td></tr>
 306  * <tr><td valign="top" headers="construct poss"><i>X</i><tt>{</tt><i>n</i><tt>}+</tt></td>
 307  *     <td headers="matches"><i>X</i>, exactly <i>n</i> times</td></tr>
 308  * <tr><td valign="top" headers="construct poss"><i>X</i><tt>{</tt><i>n</i><tt>,}+</tt></td>
 309  *     <td headers="matches"><i>X</i>, at least <i>n</i> times</td></tr>
 310  * <tr><td valign="top" headers="construct poss"><i>X</i><tt>{</tt><i>n</i><tt>,</tt><i>m</i><tt>}+</tt></td>
 311  *     <td headers="matches"><i>X</i>, at least <i>n</i> but not more than <i>m</i> times</td></tr>
 312  *
 313  * <tr><th>&nbsp;</th></tr>
 314  * <tr align="left"><th colspan="2" id="logical">Logical operators</th></tr>
 315  *
 316  * <tr><td valign="top" headers="construct logical"><i>XY</i></td>
 317  *     <td headers="matches"><i>X</i> followed by <i>Y</i></td></tr>
 318  * <tr><td valign="top" headers="construct logical"><i>X</i><tt>|</tt><i>Y</i></td>
 319  *     <td headers="matches">Either <i>X</i> or <i>Y</i></td></tr>
 320  * <tr><td valign="top" headers="construct logical"><tt>(</tt><i>X</i><tt>)</tt></td>
 321  *     <td headers="matches">X, as a <a href="#cg">capturing group</a></td></tr>
 322  *
 323  * <tr><th>&nbsp;</th></tr>
 324  * <tr align="left"><th colspan="2" id="backref">Back references</th></tr>
 325  *
 326  * <tr><td valign="bottom" headers="construct backref"><tt>\</tt><i>n</i></td>
 327  *     <td valign="bottom" headers="matches">Whatever the <i>n</i><sup>th</sup>
 328  *     <a href="#cg">capturing group</a> matched</td></tr>
 329  *
 330  * <tr><td valign="bottom" headers="construct backref"><tt>\</tt><i>k</i>&lt;<i>name</i>&gt;</td>
 331  *     <td valign="bottom" headers="matches">Whatever the
 332  *     <a href="#groupname">named-capturing group</a> "name" matched</td></tr>
 333  *
 334  * <tr><th>&nbsp;</th></tr>
 335  * <tr align="left"><th colspan="2" id="quot">Quotation</th></tr>
 336  *
 337  * <tr><td valign="top" headers="construct quot"><tt>\</tt></td>
 338  *     <td headers="matches">Nothing, but quotes the following character</td></tr>
 339  * <tr><td valign="top" headers="construct quot"><tt>\Q</tt></td>
 340  *     <td headers="matches">Nothing, but quotes all characters until <tt>\E</tt></td></tr>
 341  * <tr><td valign="top" headers="construct quot"><tt>\E</tt></td>
 342  *     <td headers="matches">Nothing, but ends quoting started by <tt>\Q</tt></td></tr>
 343  *     <!-- Metachars: !$()*+.<>?[\]^{|} -->
 344  *
 345  * <tr><th>&nbsp;</th></tr>
 346  * <tr align="left"><th colspan="2" id="special">Special constructs (named-capturing and non-capturing)</th></tr>
 347  *
 348  * <tr><td valign="top" headers="construct special"><tt>(?&lt;<a href="#groupname">name</a>&gt;</tt><i>X</i><tt>)</tt></td>
 349  *     <td headers="matches"><i>X</i>, as a named-capturing group</td></tr>
 350  * <tr><td valign="top" headers="construct special"><tt>(?:</tt><i>X</i><tt>)</tt></td>
 351  *     <td headers="matches"><i>X</i>, as a non-capturing group</td></tr>
 352  * <tr><td valign="top" headers="construct special"><tt>(?idmsuxU-idmsuxU)&nbsp;</tt></td>
 353  *     <td headers="matches">Nothing, but turns match flags <a href="#CASE_INSENSITIVE">i</a>
 354  * <a href="#UNIX_LINES">d</a> <a href="#MULTILINE">m</a> <a href="#DOTALL">s</a>
 355  * <a href="#UNICODE_CASE">u</a> <a href="#COMMENTS">x</a> <a href="#UNICODE_CHARACTER_CLASS">U</a>
 356  * on - off</td></tr>
 357  * <tr><td valign="top" headers="construct special"><tt>(?idmsux-idmsux:</tt><i>X</i><tt>)</tt>&nbsp;&nbsp;</td>
 358  *     <td headers="matches"><i>X</i>, as a <a href="#cg">non-capturing group</a> with the
 359  *         given flags <a href="#CASE_INSENSITIVE">i</a> <a href="#UNIX_LINES">d</a>
 360  * <a href="#MULTILINE">m</a> <a href="#DOTALL">s</a> <a href="#UNICODE_CASE">u</a >
 361  * <a href="#COMMENTS">x</a> on - off</td></tr>
 362  * <tr><td valign="top" headers="construct special"><tt>(?=</tt><i>X</i><tt>)</tt></td>
 363  *     <td headers="matches"><i>X</i>, via zero-width positive lookahead</td></tr>
 364  * <tr><td valign="top" headers="construct special"><tt>(?!</tt><i>X</i><tt>)</tt></td>
 365  *     <td headers="matches"><i>X</i>, via zero-width negative lookahead</td></tr>
 366  * <tr><td valign="top" headers="construct special"><tt>(?&lt;=</tt><i>X</i><tt>)</tt></td>
 367  *     <td headers="matches"><i>X</i>, via zero-width positive lookbehind</td></tr>
 368  * <tr><td valign="top" headers="construct special"><tt>(?&lt;!</tt><i>X</i><tt>)</tt></td>
 369  *     <td headers="matches"><i>X</i>, via zero-width negative lookbehind</td></tr>
 370  * <tr><td valign="top" headers="construct special"><tt>(?&gt;</tt><i>X</i><tt>)</tt></td>
 371  *     <td headers="matches"><i>X</i>, as an independent, non-capturing group</td></tr>
 372  *
 373  * </table>
 374  *
 375  * <hr>
 376  *
 377  *
 378  * <h3><a name="bs">Backslashes, escapes, and quoting</a></h3>
 379  *
 380  * <p> The backslash character (<tt>'\'</tt>) serves to introduce escaped
 381  * constructs, as defined in the table above, as well as to quote characters
 382  * that otherwise would be interpreted as unescaped constructs.  Thus the
 383  * expression <tt>\\</tt> matches a single backslash and <tt>\{</tt> matches a
 384  * left brace.
 385  *
 386  * <p> It is an error to use a backslash prior to any alphabetic character that
 387  * does not denote an escaped construct; these are reserved for future
 388  * extensions to the regular-expression language.  A backslash may be used
 389  * prior to a non-alphabetic character regardless of whether that character is
 390  * part of an unescaped construct.
 391  *
 392  * <p> Backslashes within string literals in Java source code are interpreted
 393  * as required by
 394  * <cite>The Java&trade; Language Specification</cite>
 395  * as either Unicode escapes (section 3.3) or other character escapes (section 3.10.6)
 396  * It is therefore necessary to double backslashes in string
 397  * literals that represent regular expressions to protect them from
 398  * interpretation by the Java bytecode compiler.  The string literal
 399  * <tt>"&#92;b"</tt>, for example, matches a single backspace character when
 400  * interpreted as a regular expression, while <tt>"&#92;&#92;b"</tt> matches a
 401  * word boundary.  The string literal <tt>"&#92;(hello&#92;)"</tt> is illegal
 402  * and leads to a compile-time error; in order to match the string
 403  * <tt>(hello)</tt> the string literal <tt>"&#92;&#92;(hello&#92;&#92;)"</tt>
 404  * must be used.
 405  *
 406  * <h3><a name="cc">Character Classes</a></h3>
 407  *
 408  *    <p> Character classes may appear within other character classes, and
 409  *    may be composed by the union operator (implicit) and the intersection
 410  *    operator (<tt>&amp;&amp;</tt>).
 411  *    The union operator denotes a class that contains every character that is
 412  *    in at least one of its operand classes.  The intersection operator
 413  *    denotes a class that contains every character that is in both of its
 414  *    operand classes.
 415  *
 416  *    <p> The precedence of character-class operators is as follows, from
 417  *    highest to lowest:
 418  *
 419  *    <blockquote><table border="0" cellpadding="1" cellspacing="0"
 420  *                 summary="Precedence of character class operators.">
 421  *      <tr><th>1&nbsp;&nbsp;&nbsp;&nbsp;</th>
 422  *        <td>Literal escape&nbsp;&nbsp;&nbsp;&nbsp;</td>
 423  *        <td><tt>\x</tt></td></tr>
 424  *     <tr><th>2&nbsp;&nbsp;&nbsp;&nbsp;</th>
 425  *        <td>Grouping</td>
 426  *        <td><tt>[...]</tt></td></tr>
 427  *     <tr><th>3&nbsp;&nbsp;&nbsp;&nbsp;</th>
 428  *        <td>Range</td>
 429  *        <td><tt>a-z</tt></td></tr>
 430  *      <tr><th>4&nbsp;&nbsp;&nbsp;&nbsp;</th>
 431  *        <td>Union</td>
 432  *        <td><tt>[a-e][i-u]</tt></td></tr>
 433  *      <tr><th>5&nbsp;&nbsp;&nbsp;&nbsp;</th>
 434  *        <td>Intersection</td>
 435  *        <td>{@code [a-z&&[aeiou]]}</td></tr>
 436  *    </table></blockquote>
 437  *
 438  *    <p> Note that a different set of metacharacters are in effect inside
 439  *    a character class than outside a character class. For instance, the
 440  *    regular expression <tt>.</tt> loses its special meaning inside a
 441  *    character class, while the expression <tt>-</tt> becomes a range
 442  *    forming metacharacter.
 443  *
 444  * <h3><a name="lt">Line terminators</a></h3>
 445  *
 446  * <p> A <i>line terminator</i> is a one- or two-character sequence that marks
 447  * the end of a line of the input character sequence.  The following are
 448  * recognized as line terminators:
 449  *
 450  * <ul>
 451  *
 452  *   <li> A newline (line feed) character&nbsp;(<tt>'\n'</tt>),
 453  *
 454  *   <li> A carriage-return character followed immediately by a newline
 455  *   character&nbsp;(<tt>"\r\n"</tt>),
 456  *
 457  *   <li> A standalone carriage-return character&nbsp;(<tt>'\r'</tt>),
 458  *
 459  *   <li> A next-line character&nbsp;(<tt>'&#92;u0085'</tt>),
 460  *
 461  *   <li> A line-separator character&nbsp;(<tt>'&#92;u2028'</tt>), or
 462  *
 463  *   <li> A paragraph-separator character&nbsp;(<tt>'&#92;u2029</tt>).
 464  *
 465  * </ul>
 466  * <p>If {@link #UNIX_LINES} mode is activated, then the only line terminators
 467  * recognized are newline characters.
 468  *
 469  * <p> The regular expression <tt>.</tt> matches any character except a line
 470  * terminator unless the {@link #DOTALL} flag is specified.
 471  *
 472  * <p> By default, the regular expressions <tt>^</tt> and <tt>$</tt> ignore
 473  * line terminators and only match at the beginning and the end, respectively,
 474  * of the entire input sequence. If {@link #MULTILINE} mode is activated then
 475  * <tt>^</tt> matches at the beginning of input and after any line terminator
 476  * except at the end of input. When in {@link #MULTILINE} mode <tt>$</tt>
 477  * matches just before a line terminator or the end of the input sequence.
 478  *
 479  * <h3><a name="cg">Groups and capturing</a></h3>
 480  *
 481  * <h4><a name="gnumber">Group number</a></h4>
 482  * <p> Capturing groups are numbered by counting their opening parentheses from
 483  * left to right.  In the expression <tt>((A)(B(C)))</tt>, for example, there
 484  * are four such groups: </p>
 485  *
 486  * <blockquote><table cellpadding=1 cellspacing=0 summary="Capturing group numberings">
 487  * <tr><th>1&nbsp;&nbsp;&nbsp;&nbsp;</th>
 488  *     <td><tt>((A)(B(C)))</tt></td></tr>
 489  * <tr><th>2&nbsp;&nbsp;&nbsp;&nbsp;</th>
 490  *     <td><tt>(A)</tt></td></tr>
 491  * <tr><th>3&nbsp;&nbsp;&nbsp;&nbsp;</th>
 492  *     <td><tt>(B(C))</tt></td></tr>
 493  * <tr><th>4&nbsp;&nbsp;&nbsp;&nbsp;</th>
 494  *     <td><tt>(C)</tt></td></tr>
 495  * </table></blockquote>
 496  *
 497  * <p> Group zero always stands for the entire expression.
 498  *
 499  * <p> Capturing groups are so named because, during a match, each subsequence
 500  * of the input sequence that matches such a group is saved.  The captured
 501  * subsequence may be used later in the expression, via a back reference, and
 502  * may also be retrieved from the matcher once the match operation is complete.
 503  *
 504  * <h4><a name="groupname">Group name</a></h4>
 505  * <p>A capturing group can also be assigned a "name", a <tt>named-capturing group</tt>,
 506  * and then be back-referenced later by the "name". Group names are composed of
 507  * the following characters. The first character must be a <tt>letter</tt>.
 508  *
 509  * <ul>
 510  *   <li> The uppercase letters <tt>'A'</tt> through <tt>'Z'</tt>
 511  *        (<tt>'&#92;u0041'</tt>&nbsp;through&nbsp;<tt>'&#92;u005a'</tt>),
 512  *   <li> The lowercase letters <tt>'a'</tt> through <tt>'z'</tt>
 513  *        (<tt>'&#92;u0061'</tt>&nbsp;through&nbsp;<tt>'&#92;u007a'</tt>),
 514  *   <li> The digits <tt>'0'</tt> through <tt>'9'</tt>
 515  *        (<tt>'&#92;u0030'</tt>&nbsp;through&nbsp;<tt>'&#92;u0039'</tt>),
 516  * </ul>
 517  *
 518  * <p> A <tt>named-capturing group</tt> is still numbered as described in
 519  * <a href="#gnumber">Group number</a>.
 520  *
 521  * <p> The captured input associated with a group is always the subsequence
 522  * that the group most recently matched.  If a group is evaluated a second time
 523  * because of quantification then its previously-captured value, if any, will
 524  * be retained if the second evaluation fails.  Matching the string
 525  * <tt>"aba"</tt> against the expression <tt>(a(b)?)+</tt>, for example, leaves
 526  * group two set to <tt>"b"</tt>.  All captured input is discarded at the
 527  * beginning of each match.
 528  *
 529  * <p> Groups beginning with <tt>(?</tt> are either pure, <i>non-capturing</i> groups
 530  * that do not capture text and do not count towards the group total, or
 531  * <i>named-capturing</i> group.
 532  *
 533  * <h3> Unicode support </h3>
 534  *
 535  * <p> This class is in conformance with Level 1 of <a
 536  * href="http://www.unicode.org/reports/tr18/"><i>Unicode Technical
 537  * Standard #18: Unicode Regular Expression</i></a>, plus RL2.1
 538  * Canonical Equivalents.
 539  * <p>
 540  * <b>Unicode escape sequences</b> such as <tt>&#92;u2014</tt> in Java source code
 541  * are processed as described in section 3.3 of
 542  * <cite>The Java&trade; Language Specification</cite>.
 543  * Such escape sequences are also implemented directly by the regular-expression
 544  * parser so that Unicode escapes can be used in expressions that are read from
 545  * files or from the keyboard.  Thus the strings <tt>"&#92;u2014"</tt> and
 546  * <tt>"\\u2014"</tt>, while not equal, compile into the same pattern, which
 547  * matches the character with hexadecimal value <tt>0x2014</tt>.
 548  * <p>
 549  * A Unicode character can also be represented in a regular-expression by
 550  * using its <b>Hex notation</b>(hexadecimal code point value) directly as described in construct
 551  * <tt>&#92;x{...}</tt>, for example a supplementary character U+2011F
 552  * can be specified as <tt>&#92;x{2011F}</tt>, instead of two consecutive
 553  * Unicode escape sequences of the surrogate pair
 554  * <tt>&#92;uD840</tt><tt>&#92;uDD1F</tt>.
 555  * <p>
 556  * Unicode scripts, blocks, categories and binary properties are written with
 557  * the <tt>\p</tt> and <tt>\P</tt> constructs as in Perl.
 558  * <tt>\p{</tt><i>prop</i><tt>}</tt> matches if
 559  * the input has the property <i>prop</i>, while <tt>\P{</tt><i>prop</i><tt>}</tt>
 560  * does not match if the input has that property.
 561  * <p>
 562  * Scripts, blocks, categories and binary properties can be used both inside
 563  * and outside of a character class.
 564  *
 565  * <p>
 566  * <b><a name="usc">Scripts</a></b> are specified either with the prefix {@code Is}, as in
 567  * {@code IsHiragana}, or by using  the {@code script} keyword (or its short
 568  * form {@code sc})as in {@code script=Hiragana} or {@code sc=Hiragana}.
 569  * <p>
 570  * The script names supported by <code>Pattern</code> are the valid script names
 571  * accepted and defined by
 572  * {@link java.lang.Character.UnicodeScript#forName(String) UnicodeScript.forName}.
 573  *
 574  * <p>
 575  * <b><a name="ubc">Blocks</a></b> are specified with the prefix {@code In}, as in
 576  * {@code InMongolian}, or by using the keyword {@code block} (or its short
 577  * form {@code blk}) as in {@code block=Mongolian} or {@code blk=Mongolian}.
 578  * <p>
 579  * The block names supported by <code>Pattern</code> are the valid block names
 580  * accepted and defined by
 581  * {@link java.lang.Character.UnicodeBlock#forName(String) UnicodeBlock.forName}.
 582  * <p>
 583  *
 584  * <b><a name="ucc">Categories</a></b> may be specified with the optional prefix {@code Is}:
 585  * Both {@code \p{L}} and {@code \p{IsL}} denote the category of Unicode
 586  * letters. Same as scripts and blocks, categories can also be specified
 587  * by using the keyword {@code general_category} (or its short form
 588  * {@code gc}) as in {@code general_category=Lu} or {@code gc=Lu}.
 589  * <p>
 590  * The supported categories are those of
 591  * <a href="http://www.unicode.org/unicode/standard/standard.html">
 592  * <i>The Unicode Standard</i></a> in the version specified by the
 593  * {@link java.lang.Character Character} class. The category names are those
 594  * defined in the Standard, both normative and informative.
 595  * <p>
 596  *
 597  * <b><a name="ubpc">Binary properties</a></b> are specified with the prefix {@code Is}, as in
 598  * {@code IsAlphabetic}. The supported binary properties by <code>Pattern</code>
 599  * are
 600  * <ul>
 601  *   <li> Alphabetic
 602  *   <li> Ideographic
 603  *   <li> Letter
 604  *   <li> Lowercase
 605  *   <li> Uppercase
 606  *   <li> Titlecase
 607  *   <li> Punctuation
 608  *   <Li> Control
 609  *   <li> White_Space
 610  *   <li> Digit
 611  *   <li> Hex_Digit
 612  *   <li> Join_Control
 613  *   <li> Noncharacter_Code_Point
 614  *   <li> Assigned
 615  * </ul>
 616  * <p>
 617  * The following <b>Predefined Character classes</b> and <b>POSIX character classes</b>
 618  * are in conformance with the recommendation of <i>Annex C: Compatibility Properties</i>
 619  * of <a href="http://www.unicode.org/reports/tr18/"><i>Unicode Regular Expression
 620  * </i></a>, when {@link #UNICODE_CHARACTER_CLASS} flag is specified.
 621  *
 622  * <table border="0" cellpadding="1" cellspacing="0"
 623  *  summary="predefined and posix character classes in Unicode mode">
 624  * <tr align="left">
 625  * <th align="left" id="predef_classes">Classes</th>
 626  * <th align="left" id="predef_matches">Matches</th>
 627  *</tr>
 628  * <tr><td><tt>\p{Lower}</tt></td>
 629  *     <td>A lowercase character:<tt>\p{IsLowercase}</tt></td></tr>
 630  * <tr><td><tt>\p{Upper}</tt></td>
 631  *     <td>An uppercase character:<tt>\p{IsUppercase}</tt></td></tr>
 632  * <tr><td><tt>\p{ASCII}</tt></td>
 633  *     <td>All ASCII:<tt>[\x00-\x7F]</tt></td></tr>
 634  * <tr><td><tt>\p{Alpha}</tt></td>
 635  *     <td>An alphabetic character:<tt>\p{IsAlphabetic}</tt></td></tr>
 636  * <tr><td><tt>\p{Digit}</tt></td>
 637  *     <td>A decimal digit character:<tt>p{IsDigit}</tt></td></tr>
 638  * <tr><td><tt>\p{Alnum}</tt></td>
 639  *     <td>An alphanumeric character:<tt>[\p{IsAlphabetic}\p{IsDigit}]</tt></td></tr>
 640  * <tr><td><tt>\p{Punct}</tt></td>
 641  *     <td>A punctuation character:<tt>p{IsPunctuation}</tt></td></tr>
 642  * <tr><td><tt>\p{Graph}</tt></td>
 643  *     <td>A visible character: <tt>[^\p{IsWhite_Space}\p{gc=Cc}\p{gc=Cs}\p{gc=Cn}]</tt></td></tr>
 644  * <tr><td><tt>\p{Print}</tt></td>
 645  *     <td>A printable character: {@code [\p{Graph}\p{Blank}&&[^\p{Cntrl}]]}</td></tr>
 646  * <tr><td><tt>\p{Blank}</tt></td>
 647  *     <td>A space or a tab: {@code [\p{IsWhite_Space}&&[^\p{gc=Zl}\p{gc=Zp}\x0a\x0b\x0c\x0d\x85]]}</td></tr>
 648  * <tr><td><tt>\p{Cntrl}</tt></td>
 649  *     <td>A control character: <tt>\p{gc=Cc}</tt></td></tr>
 650  * <tr><td><tt>\p{XDigit}</tt></td>
 651  *     <td>A hexadecimal digit: <tt>[\p{gc=Nd}\p{IsHex_Digit}]</tt></td></tr>
 652  * <tr><td><tt>\p{Space}</tt></td>
 653  *     <td>A whitespace character:<tt>\p{IsWhite_Space}</tt></td></tr>
 654  * <tr><td><tt>\d</tt></td>
 655  *     <td>A digit: <tt>\p{IsDigit}</tt></td></tr>
 656  * <tr><td><tt>\D</tt></td>
 657  *     <td>A non-digit: <tt>[^\d]</tt></td></tr>
 658  * <tr><td><tt>\s</tt></td>
 659  *     <td>A whitespace character: <tt>\p{IsWhite_Space}</tt></td></tr>
 660  * <tr><td><tt>\S</tt></td>
 661  *     <td>A non-whitespace character: <tt>[^\s]</tt></td></tr>
 662  * <tr><td><tt>\w</tt></td>
 663  *     <td>A word character: <tt>[\p{Alpha}\p{gc=Mn}\p{gc=Me}\p{gc=Mc}\p{Digit}\p{gc=Pc}\p{IsJoin_Control}]</tt></td></tr>
 664  * <tr><td><tt>\W</tt></td>
 665  *     <td>A non-word character: <tt>[^\w]</tt></td></tr>
 666  * </table>
 667  * <p>
 668  * <a name="jcc">
 669  * Categories that behave like the java.lang.Character
 670  * boolean is<i>methodname</i> methods (except for the deprecated ones) are
 671  * available through the same <tt>\p{</tt><i>prop</i><tt>}</tt> syntax where
 672  * the specified property has the name <tt>java<i>methodname</i></tt></a>.
 673  *
 674  * <h3> Comparison to Perl 5 </h3>
 675  *
 676  * <p>The <code>Pattern</code> engine performs traditional NFA-based matching
 677  * with ordered alternation as occurs in Perl 5.
 678  *
 679  * <p> Perl constructs not supported by this class: </p>
 680  *
 681  * <ul>
 682  *    <li><p> Predefined character classes (Unicode character)
 683  *    <p><tt>\X&nbsp;&nbsp;&nbsp;&nbsp;</tt>Match Unicode
 684  *    <a href="http://www.unicode.org/reports/tr18/#Default_Grapheme_Clusters">
 685  *    <i>extended grapheme cluster</i></a>
 686  *    </p></li>
 687  *
 688  *    <li><p> The backreference constructs, <tt>\g{</tt><i>n</i><tt>}</tt> for
 689  *    the <i>n</i><sup>th</sup><a href="#cg">capturing group</a> and
 690  *    <tt>\g{</tt><i>name</i><tt>}</tt> for
 691  *    <a href="#groupname">named-capturing group</a>.
 692  *    </p></li>
 693  *
 694  *    <li><p> The named character construct, <tt>\N{</tt><i>name</i><tt>}</tt>
 695  *    for a Unicode character by its name.
 696  *    </p></li>
 697  *
 698  *    <li><p> The conditional constructs
 699  *    <tt>(?(</tt><i>condition</i><tt>)</tt><i>X</i><tt>)</tt> and
 700  *    <tt>(?(</tt><i>condition</i><tt>)</tt><i>X</i><tt>|</tt><i>Y</i><tt>)</tt>,
 701  *    </p></li>
 702  *
 703  *    <li><p> The embedded code constructs <tt>(?{</tt><i>code</i><tt>})</tt>
 704  *    and <tt>(??{</tt><i>code</i><tt>})</tt>,</p></li>
 705  *
 706  *    <li><p> The embedded comment syntax <tt>(?#comment)</tt>, and </p></li>
 707  *
 708  *    <li><p> The preprocessing operations <tt>\l</tt> <tt>&#92;u</tt>,
 709  *    <tt>\L</tt>, and <tt>\U</tt>.  </p></li>
 710  *
 711  * </ul>
 712  *
 713  * <p> Constructs supported by this class but not by Perl: </p>
 714  *
 715  * <ul>
 716  *
 717  *    <li><p> Character-class union and intersection as described
 718  *    <a href="#cc">above</a>.</p></li>
 719  *
 720  * </ul>
 721  *
 722  * <p> Notable differences from Perl: </p>
 723  *
 724  * <ul>
 725  *
 726  *    <li><p> In Perl, <tt>\1</tt> through <tt>\9</tt> are always interpreted
 727  *    as back references; a backslash-escaped number greater than <tt>9</tt> is
 728  *    treated as a back reference if at least that many subexpressions exist,
 729  *    otherwise it is interpreted, if possible, as an octal escape.  In this
 730  *    class octal escapes must always begin with a zero. In this class,
 731  *    <tt>\1</tt> through <tt>\9</tt> are always interpreted as back
 732  *    references, and a larger number is accepted as a back reference if at
 733  *    least that many subexpressions exist at that point in the regular
 734  *    expression, otherwise the parser will drop digits until the number is
 735  *    smaller or equal to the existing number of groups or it is one digit.
 736  *    </p></li>
 737  *
 738  *    <li><p> Perl uses the <tt>g</tt> flag to request a match that resumes
 739  *    where the last match left off.  This functionality is provided implicitly
 740  *    by the {@link Matcher} class: Repeated invocations of the {@link
 741  *    Matcher#find find} method will resume where the last match left off,
 742  *    unless the matcher is reset.  </p></li>
 743  *
 744  *    <li><p> In Perl, embedded flags at the top level of an expression affect
 745  *    the whole expression.  In this class, embedded flags always take effect
 746  *    at the point at which they appear, whether they are at the top level or
 747  *    within a group; in the latter case, flags are restored at the end of the
 748  *    group just as in Perl.  </p></li>
 749  *
 750  * </ul>
 751  *
 752  *
 753  * <p> For a more precise description of the behavior of regular expression
 754  * constructs, please see <a href="http://www.oreilly.com/catalog/regex3/">
 755  * <i>Mastering Regular Expressions, 3nd Edition</i>, Jeffrey E. F. Friedl,
 756  * O'Reilly and Associates, 2006.</a>
 757  * </p>
 758  *
 759  * @see java.lang.String#split(String, int)
 760  * @see java.lang.String#split(String)
 761  *
 762  * @author      Mike McCloskey
 763  * @author      Mark Reinhold
 764  * @author      JSR-51 Expert Group
 765  * @since       1.4
 766  * @spec        JSR-51
 767  */
 768 
 769 public final class Pattern
 770     implements java.io.Serializable
 771 {
 772 
 773     /**
 774      * Regular expression modifier values.  Instead of being passed as
 775      * arguments, they can also be passed as inline modifiers.
 776      * For example, the following statements have the same effect.
 777      * <pre>
 778      * RegExp r1 = RegExp.compile("abc", Pattern.I|Pattern.M);
 779      * RegExp r2 = RegExp.compile("(?im)abc", 0);
 780      * </pre>
 781      *
 782      * The flags are duplicated so that the familiar Perl match flag
 783      * names are available.
 784      */
 785 
 786     /**
 787      * Enables Unix lines mode.
 788      *
 789      * <p> In this mode, only the <tt>'\n'</tt> line terminator is recognized
 790      * in the behavior of <tt>.</tt>, <tt>^</tt>, and <tt>$</tt>.
 791      *
 792      * <p> Unix lines mode can also be enabled via the embedded flag
 793      * expression&nbsp;<tt>(?d)</tt>.
 794      */
 795     public static final int UNIX_LINES = 0x01;
 796 
 797     /**
 798      * Enables case-insensitive matching.
 799      *
 800      * <p> By default, case-insensitive matching assumes that only characters
 801      * in the US-ASCII charset are being matched.  Unicode-aware
 802      * case-insensitive matching can be enabled by specifying the {@link
 803      * #UNICODE_CASE} flag in conjunction with this flag.
 804      *
 805      * <p> Case-insensitive matching can also be enabled via the embedded flag
 806      * expression&nbsp;<tt>(?i)</tt>.
 807      *
 808      * <p> Specifying this flag may impose a slight performance penalty.  </p>
 809      */
 810     public static final int CASE_INSENSITIVE = 0x02;
 811 
 812     /**
 813      * Permits whitespace and comments in pattern.
 814      *
 815      * <p> In this mode, whitespace is ignored, and embedded comments starting
 816      * with <tt>#</tt> are ignored until the end of a line.
 817      *
 818      * <p> Comments mode can also be enabled via the embedded flag
 819      * expression&nbsp;<tt>(?x)</tt>.
 820      */
 821     public static final int COMMENTS = 0x04;
 822 
 823     /**
 824      * Enables multiline mode.
 825      *
 826      * <p> In multiline mode the expressions <tt>^</tt> and <tt>$</tt> match
 827      * just after or just before, respectively, a line terminator or the end of
 828      * the input sequence.  By default these expressions only match at the
 829      * beginning and the end of the entire input sequence.
 830      *
 831      * <p> Multiline mode can also be enabled via the embedded flag
 832      * expression&nbsp;<tt>(?m)</tt>.  </p>
 833      */
 834     public static final int MULTILINE = 0x08;
 835 
 836     /**
 837      * Enables literal parsing of the pattern.
 838      *
 839      * <p> When this flag is specified then the input string that specifies
 840      * the pattern is treated as a sequence of literal characters.
 841      * Metacharacters or escape sequences in the input sequence will be
 842      * given no special meaning.
 843      *
 844      * <p>The flags CASE_INSENSITIVE and UNICODE_CASE retain their impact on
 845      * matching when used in conjunction with this flag. The other flags
 846      * become superfluous.
 847      *
 848      * <p> There is no embedded flag character for enabling literal parsing.
 849      * @since 1.5
 850      */
 851     public static final int LITERAL = 0x10;
 852 
 853     /**
 854      * Enables dotall mode.
 855      *
 856      * <p> In dotall mode, the expression <tt>.</tt> matches any character,
 857      * including a line terminator.  By default this expression does not match
 858      * line terminators.
 859      *
 860      * <p> Dotall mode can also be enabled via the embedded flag
 861      * expression&nbsp;<tt>(?s)</tt>.  (The <tt>s</tt> is a mnemonic for
 862      * "single-line" mode, which is what this is called in Perl.)  </p>
 863      */
 864     public static final int DOTALL = 0x20;
 865 
 866     /**
 867      * Enables Unicode-aware case folding.
 868      *
 869      * <p> When this flag is specified then case-insensitive matching, when
 870      * enabled by the {@link #CASE_INSENSITIVE} flag, is done in a manner
 871      * consistent with the Unicode Standard.  By default, case-insensitive
 872      * matching assumes that only characters in the US-ASCII charset are being
 873      * matched.
 874      *
 875      * <p> Unicode-aware case folding can also be enabled via the embedded flag
 876      * expression&nbsp;<tt>(?u)</tt>.
 877      *
 878      * <p> Specifying this flag may impose a performance penalty.  </p>
 879      */
 880     public static final int UNICODE_CASE = 0x40;
 881 
 882     /**
 883      * Enables canonical equivalence.
 884      *
 885      * <p> When this flag is specified then two characters will be considered
 886      * to match if, and only if, their full canonical decompositions match.
 887      * The expression <tt>"a&#92;u030A"</tt>, for example, will match the
 888      * string <tt>"&#92;u00E5"</tt> when this flag is specified.  By default,
 889      * matching does not take canonical equivalence into account.
 890      *
 891      * <p> There is no embedded flag character for enabling canonical
 892      * equivalence.
 893      *
 894      * <p> Specifying this flag may impose a performance penalty.  </p>
 895      */
 896     public static final int CANON_EQ = 0x80;
 897 
 898     /**
 899      * Enables the Unicode version of <i>Predefined character classes</i> and
 900      * <i>POSIX character classes</i>.
 901      *
 902      * <p> When this flag is specified then the (US-ASCII only)
 903      * <i>Predefined character classes</i> and <i>POSIX character classes</i>
 904      * are in conformance with
 905      * <a href="http://www.unicode.org/reports/tr18/"><i>Unicode Technical
 906      * Standard #18: Unicode Regular Expression</i></a>
 907      * <i>Annex C: Compatibility Properties</i>.
 908      * <p>
 909      * The UNICODE_CHARACTER_CLASS mode can also be enabled via the embedded
 910      * flag expression&nbsp;<tt>(?U)</tt>.
 911      * <p>
 912      * The flag implies UNICODE_CASE, that is, it enables Unicode-aware case
 913      * folding.
 914      * <p>
 915      * Specifying this flag may impose a performance penalty.  </p>
 916      * @since 1.7
 917      */
 918     public static final int UNICODE_CHARACTER_CLASS = 0x100;
 919 
 920     /* Pattern has only two serialized components: The pattern string
 921      * and the flags, which are all that is needed to recompile the pattern
 922      * when it is deserialized.
 923      */
 924 
 925     /** use serialVersionUID from Merlin b59 for interoperability */
 926     private static final long serialVersionUID = 5073258162644648461L;
 927 
 928     /**
 929      * The original regular-expression pattern string.
 930      *
 931      * @serial
 932      */
 933     private String pattern;
 934 
 935     /**
 936      * The original pattern flags.
 937      *
 938      * @serial
 939      */
 940     private int flags;
 941 
 942     /**
 943      * Boolean indicating this Pattern is compiled; this is necessary in order
 944      * to lazily compile deserialized Patterns.
 945      */
 946     private transient volatile boolean compiled = false;
 947 
 948     /**
 949      * The normalized pattern string.
 950      */
 951     private transient String normalizedPattern;
 952 
 953     /**
 954      * The starting point of state machine for the find operation.  This allows
 955      * a match to start anywhere in the input.
 956      */
 957     transient Node root;
 958 
 959     /**
 960      * The root of object tree for a match operation.  The pattern is matched
 961      * at the beginning.  This may include a find that uses BnM or a First
 962      * node.
 963      */
 964     transient Node matchRoot;
 965 
 966     /**
 967      * Temporary storage used by parsing pattern slice.
 968      */
 969     transient int[] buffer;
 970 
 971     /**
 972      * Map the "name" of the "named capturing group" to its group id
 973      * node.
 974      */
 975     transient volatile Map<String, Integer> namedGroups;
 976 
 977     /**
 978      * Temporary storage used while parsing group references.
 979      */
 980     transient GroupHead[] groupNodes;
 981 
 982     /**
 983      * Temporary null terminated code point array used by pattern compiling.
 984      */
 985     private transient int[] temp;
 986 
 987     /**
 988      * The number of capturing groups in this Pattern. Used by matchers to
 989      * allocate storage needed to perform a match.
 990      */
 991     transient int capturingGroupCount;
 992 
 993     /**
 994      * The local variable count used by parsing tree. Used by matchers to
 995      * allocate storage needed to perform a match.
 996      */
 997     transient int localCount;
 998 
 999     /**
1000      * Index into the pattern string that keeps track of how much has been
1001      * parsed.
1002      */
1003     private transient int cursor;
1004 
1005     /**
1006      * Holds the length of the pattern string.
1007      */
1008     private transient int patternLength;
1009 
1010     /**
1011      * If the Start node might possibly match supplementary characters.
1012      * It is set to true during compiling if
1013      * (1) There is supplementary char in pattern, or
1014      * (2) There is complement node of Category or Block
1015      */
1016     private transient boolean hasSupplementary;
1017 
1018     /**
1019      * Compiles the given regular expression into a pattern.
1020      *
1021      * @param  regex
1022      *         The expression to be compiled
1023      * @return the given regular expression compiled into a pattern
1024      * @throws  PatternSyntaxException
1025      *          If the expression's syntax is invalid
1026      */
1027     public static Pattern compile(String regex) {
1028         return new Pattern(regex, 0);
1029     }
1030 
1031     /**
1032      * Compiles the given regular expression into a pattern with the given
1033      * flags.
1034      *
1035      * @param  regex
1036      *         The expression to be compiled
1037      *
1038      * @param  flags
1039      *         Match flags, a bit mask that may include
1040      *         {@link #CASE_INSENSITIVE}, {@link #MULTILINE}, {@link #DOTALL},
1041      *         {@link #UNICODE_CASE}, {@link #CANON_EQ}, {@link #UNIX_LINES},
1042      *         {@link #LITERAL}, {@link #UNICODE_CHARACTER_CLASS}
1043      *         and {@link #COMMENTS}
1044      *
1045      * @return the given regular expression compiled into a pattern with the given flags
1046      * @throws  IllegalArgumentException
1047      *          If bit values other than those corresponding to the defined
1048      *          match flags are set in <tt>flags</tt>
1049      *
1050      * @throws  PatternSyntaxException
1051      *          If the expression's syntax is invalid
1052      */
1053     public static Pattern compile(String regex, int flags) {
1054         return new Pattern(regex, flags);
1055     }
1056 
1057     /**
1058      * Returns the regular expression from which this pattern was compiled.
1059      *
1060      * @return  The source of this pattern
1061      */
1062     public String pattern() {
1063         return pattern;
1064     }
1065 
1066     /**
1067      * <p>Returns the string representation of this pattern. This
1068      * is the regular expression from which this pattern was
1069      * compiled.</p>
1070      *
1071      * @return  The string representation of this pattern
1072      * @since 1.5
1073      */
1074     public String toString() {
1075         return pattern;
1076     }
1077 
1078     /**
1079      * Creates a matcher that will match the given input against this pattern.
1080      *
1081      * @param  input
1082      *         The character sequence to be matched
1083      *
1084      * @return  A new matcher for this pattern
1085      */
1086     public Matcher matcher(CharSequence input) {
1087         if (!compiled) {
1088             synchronized(this) {
1089                 if (!compiled)
1090                     compile();
1091             }
1092         }
1093         Matcher m = new Matcher(this, input);
1094         return m;
1095     }
1096 
1097     /**
1098      * Returns this pattern's match flags.
1099      *
1100      * @return  The match flags specified when this pattern was compiled
1101      */
1102     public int flags() {
1103         return flags;
1104     }
1105 
1106     /**
1107      * Compiles the given regular expression and attempts to match the given
1108      * input against it.
1109      *
1110      * <p> An invocation of this convenience method of the form
1111      *
1112      * <blockquote><pre>
1113      * Pattern.matches(regex, input);</pre></blockquote>
1114      *
1115      * behaves in exactly the same way as the expression
1116      *
1117      * <blockquote><pre>
1118      * Pattern.compile(regex).matcher(input).matches()</pre></blockquote>
1119      *
1120      * <p> If a pattern is to be used multiple times, compiling it once and reusing
1121      * it will be more efficient than invoking this method each time.  </p>
1122      *
1123      * @param  regex
1124      *         The expression to be compiled
1125      *
1126      * @param  input
1127      *         The character sequence to be matched
1128      * @return whether or not the regular expression matches on the input
1129      * @throws  PatternSyntaxException
1130      *          If the expression's syntax is invalid
1131      */
1132     public static boolean matches(String regex, CharSequence input) {
1133         Pattern p = Pattern.compile(regex);
1134         Matcher m = p.matcher(input);
1135         return m.matches();
1136     }
1137 
1138     /**
1139      * Splits the given input sequence around matches of this pattern.
1140      *
1141      * <p> The array returned by this method contains each substring of the
1142      * input sequence that is terminated by another subsequence that matches
1143      * this pattern or is terminated by the end of the input sequence.  The
1144      * substrings in the array are in the order in which they occur in the
1145      * input. If this pattern does not match any subsequence of the input then
1146      * the resulting array has just one element, namely the input sequence in
1147      * string form. A zero-length input sequence always results zero-length
1148      * resulting array.
1149      *
1150      * <p> When there is a positive-width match at the beginning of the input
1151      * sequence then an empty leading substring is included at the beginning
1152      * of the resulting array. A zero-width match at the beginning however
1153      * never produces such empty leading substring.
1154      *
1155      * <p> The <tt>limit</tt> parameter controls the number of times the
1156      * pattern is applied and therefore affects the length of the resulting
1157      * array.  If the limit <i>n</i> is greater than zero then the pattern
1158      * will be applied at most <i>n</i>&nbsp;-&nbsp;1 times, the array's
1159      * length will be no greater than <i>n</i>, and the array's last entry
1160      * will contain all input beyond the last matched delimiter.  If <i>n</i>
1161      * is non-positive then the pattern will be applied as many times as
1162      * possible and the array can have any length.  If <i>n</i> is zero then
1163      * the pattern will be applied as many times as possible, the array can
1164      * have any length, and trailing empty strings will be discarded.
1165      *
1166      * <p> The input <tt>"boo:and:foo"</tt>, for example, yields the following
1167      * results with these parameters:
1168      *
1169      * <blockquote><table cellpadding=1 cellspacing=0
1170      *              summary="Split examples showing regex, limit, and result">
1171      * <tr><th align="left"><i>Regex&nbsp;&nbsp;&nbsp;&nbsp;</i></th>
1172      *     <th align="left"><i>Limit&nbsp;&nbsp;&nbsp;&nbsp;</i></th>
1173      *     <th align="left"><i>Result&nbsp;&nbsp;&nbsp;&nbsp;</i></th></tr>
1174      * <tr><td align=center>:</td>
1175      *     <td align=center>2</td>
1176      *     <td><tt>{ "boo", "and:foo" }</tt></td></tr>
1177      * <tr><td align=center>:</td>
1178      *     <td align=center>5</td>
1179      *     <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
1180      * <tr><td align=center>:</td>
1181      *     <td align=center>-2</td>
1182      *     <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
1183      * <tr><td align=center>o</td>
1184      *     <td align=center>5</td>
1185      *     <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
1186      * <tr><td align=center>o</td>
1187      *     <td align=center>-2</td>
1188      *     <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
1189      * <tr><td align=center>o</td>
1190      *     <td align=center>0</td>
1191      *     <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
1192      * </table></blockquote>
1193      *
1194      * @param  input
1195      *         The character sequence to be split
1196      *
1197      * @param  limit
1198      *         The result threshold, as described above
1199      *
1200      * @return  The array of strings computed by splitting the input
1201      *          around matches of this pattern
1202      */
1203     public String[] split(CharSequence input, int limit) {
1204         if (input.length() == 0)
1205             return new String[0];
1206         int index = 0;
1207         boolean matchLimited = limit > 0;
1208         ArrayList<String> matchList = new ArrayList<>();
1209         Matcher m = matcher(input);
1210 
1211         // Add segments before each match found
1212         while(m.find()) {
1213             if (!matchLimited || matchList.size() < limit - 1) {
1214                 if (index == 0 && index == m.start() && m.start() == m.end()) {
1215                     // no empty leading substring included for zero-width match
1216                     // at the beginning of the input char sequence.
1217                     continue;
1218                 }
1219                 String match = input.subSequence(index, m.start()).toString();
1220                 matchList.add(match);
1221                 index = m.end();
1222             } else if (matchList.size() == limit - 1) { // last one
1223                 String match = input.subSequence(index,
1224                                                  input.length()).toString();
1225                 matchList.add(match);
1226                 index = m.end();
1227             }
1228         }
1229 
1230         // If no match was found, return this
1231         if (index == 0)
1232             return new String[] {input.toString()};
1233 
1234         // Add remaining segment
1235         if (!matchLimited || matchList.size() < limit)
1236             matchList.add(input.subSequence(index, input.length()).toString());
1237 
1238         // Construct result
1239         int resultSize = matchList.size();
1240         if (limit == 0)
1241             while (resultSize > 0 && matchList.get(resultSize-1).equals(""))
1242                 resultSize--;
1243         String[] result = new String[resultSize];
1244         return matchList.subList(0, resultSize).toArray(result);
1245     }
1246 
1247     /**
1248      * Splits the given input sequence around matches of this pattern.
1249      *
1250      * <p> This method works as if by invoking the two-argument {@link
1251      * #split(java.lang.CharSequence, int) split} method with the given input
1252      * sequence and a limit argument of zero.  Trailing empty strings are
1253      * therefore not included in the resulting array. </p>
1254      *
1255      * <p> The input <tt>"boo:and:foo"</tt>, for example, yields the following
1256      * results with these expressions:
1257      *
1258      * <blockquote><table cellpadding=1 cellspacing=0
1259      *              summary="Split examples showing regex and result">
1260      * <tr><th align="left"><i>Regex&nbsp;&nbsp;&nbsp;&nbsp;</i></th>
1261      *     <th align="left"><i>Result</i></th></tr>
1262      * <tr><td align=center>:</td>
1263      *     <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
1264      * <tr><td align=center>o</td>
1265      *     <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
1266      * </table></blockquote>
1267      *
1268      *
1269      * @param  input
1270      *         The character sequence to be split
1271      *
1272      * @return  The array of strings computed by splitting the input
1273      *          around matches of this pattern
1274      */
1275     public String[] split(CharSequence input) {
1276         return split(input, 0);
1277     }
1278 
1279     /**
1280      * Returns a literal pattern <code>String</code> for the specified
1281      * <code>String</code>.
1282      *
1283      * <p>This method produces a <code>String</code> that can be used to
1284      * create a <code>Pattern</code> that would match the string
1285      * <code>s</code> as if it were a literal pattern.</p> Metacharacters
1286      * or escape sequences in the input sequence will be given no special
1287      * meaning.
1288      *
1289      * @param  s The string to be literalized
1290      * @return  A literal string replacement
1291      * @since 1.5
1292      */
1293     public static String quote(String s) {
1294         int slashEIndex = s.indexOf("\\E");
1295         if (slashEIndex == -1)
1296             return "\\Q" + s + "\\E";
1297 
1298         StringBuilder sb = new StringBuilder(s.length() * 2);
1299         sb.append("\\Q");
1300         slashEIndex = 0;
1301         int current = 0;
1302         while ((slashEIndex = s.indexOf("\\E", current)) != -1) {
1303             sb.append(s.substring(current, slashEIndex));
1304             current = slashEIndex + 2;
1305             sb.append("\\E\\\\E\\Q");
1306         }
1307         sb.append(s.substring(current, s.length()));
1308         sb.append("\\E");
1309         return sb.toString();
1310     }
1311 
1312     /**
1313      * Recompile the Pattern instance from a stream.  The original pattern
1314      * string is read in and the object tree is recompiled from it.
1315      */
1316     private void readObject(java.io.ObjectInputStream s)
1317         throws java.io.IOException, ClassNotFoundException {
1318 
1319         // Read in all fields
1320         s.defaultReadObject();
1321 
1322         // Initialize counts
1323         capturingGroupCount = 1;
1324         localCount = 0;
1325 
1326         // if length > 0, the Pattern is lazily compiled
1327         compiled = false;
1328         if (pattern.length() == 0) {
1329             root = new Start(lastAccept);
1330             matchRoot = lastAccept;
1331             compiled = true;
1332         }
1333     }
1334 
1335     /**
1336      * This private constructor is used to create all Patterns. The pattern
1337      * string and match flags are all that is needed to completely describe
1338      * a Pattern. An empty pattern string results in an object tree with
1339      * only a Start node and a LastNode node.
1340      */
1341     private Pattern(String p, int f) {
1342         pattern = p;
1343         flags = f;
1344 
1345         // to use UNICODE_CASE if UNICODE_CHARACTER_CLASS present
1346         if ((flags & UNICODE_CHARACTER_CLASS) != 0)
1347             flags |= UNICODE_CASE;
1348 
1349         // Reset group index count
1350         capturingGroupCount = 1;
1351         localCount = 0;
1352 
1353         if (pattern.length() > 0) {
1354             compile();
1355         } else {
1356             root = new Start(lastAccept);
1357             matchRoot = lastAccept;
1358         }
1359     }
1360 
1361     /**
1362      * The pattern is converted to normalizedD form and then a pure group
1363      * is constructed to match canonical equivalences of the characters.
1364      */
1365     private void normalize() {
1366         boolean inCharClass = false;
1367         int lastCodePoint = -1;
1368 
1369         // Convert pattern into normalizedD form
1370         normalizedPattern = Normalizer.normalize(pattern, Normalizer.Form.NFD);
1371         patternLength = normalizedPattern.length();
1372 
1373         // Modify pattern to match canonical equivalences
1374         StringBuilder newPattern = new StringBuilder(patternLength);
1375         for(int i=0; i<patternLength; ) {
1376             int c = normalizedPattern.codePointAt(i);
1377             StringBuilder sequenceBuffer;
1378             if ((Character.getType(c) == Character.NON_SPACING_MARK)
1379                 && (lastCodePoint != -1)) {
1380                 sequenceBuffer = new StringBuilder();
1381                 sequenceBuffer.appendCodePoint(lastCodePoint);
1382                 sequenceBuffer.appendCodePoint(c);
1383                 while(Character.getType(c) == Character.NON_SPACING_MARK) {
1384                     i += Character.charCount(c);
1385                     if (i >= patternLength)
1386                         break;
1387                     c = normalizedPattern.codePointAt(i);
1388                     sequenceBuffer.appendCodePoint(c);
1389                 }
1390                 String ea = produceEquivalentAlternation(
1391                                                sequenceBuffer.toString());
1392                 newPattern.setLength(newPattern.length()-Character.charCount(lastCodePoint));
1393                 newPattern.append("(?:").append(ea).append(")");
1394             } else if (c == '[' && lastCodePoint != '\\') {
1395                 i = normalizeCharClass(newPattern, i);
1396             } else {
1397                 newPattern.appendCodePoint(c);
1398             }
1399             lastCodePoint = c;
1400             i += Character.charCount(c);
1401         }
1402         normalizedPattern = newPattern.toString();
1403     }
1404 
1405     /**
1406      * Complete the character class being parsed and add a set
1407      * of alternations to it that will match the canonical equivalences
1408      * of the characters within the class.
1409      */
1410     private int normalizeCharClass(StringBuilder newPattern, int i) {
1411         StringBuilder charClass = new StringBuilder();
1412         StringBuilder eq = null;
1413         int lastCodePoint = -1;
1414         String result;
1415 
1416         i++;
1417         charClass.append("[");
1418         while(true) {
1419             int c = normalizedPattern.codePointAt(i);
1420             StringBuilder sequenceBuffer;
1421 
1422             if (c == ']' && lastCodePoint != '\\') {
1423                 charClass.append((char)c);
1424                 break;
1425             } else if (Character.getType(c) == Character.NON_SPACING_MARK) {
1426                 sequenceBuffer = new StringBuilder();
1427                 sequenceBuffer.appendCodePoint(lastCodePoint);
1428                 while(Character.getType(c) == Character.NON_SPACING_MARK) {
1429                     sequenceBuffer.appendCodePoint(c);
1430                     i += Character.charCount(c);
1431                     if (i >= normalizedPattern.length())
1432                         break;
1433                     c = normalizedPattern.codePointAt(i);
1434                 }
1435                 String ea = produceEquivalentAlternation(
1436                                                   sequenceBuffer.toString());
1437 
1438                 charClass.setLength(charClass.length()-Character.charCount(lastCodePoint));
1439                 if (eq == null)
1440                     eq = new StringBuilder();
1441                 eq.append('|');
1442                 eq.append(ea);
1443             } else {
1444                 charClass.appendCodePoint(c);
1445                 i++;
1446             }
1447             if (i == normalizedPattern.length())
1448                 throw error("Unclosed character class");
1449             lastCodePoint = c;
1450         }
1451 
1452         if (eq != null) {
1453             result = "(?:"+charClass.toString()+eq.toString()+")";
1454         } else {
1455             result = charClass.toString();
1456         }
1457 
1458         newPattern.append(result);
1459         return i;
1460     }
1461 
1462     /**
1463      * Given a specific sequence composed of a regular character and
1464      * combining marks that follow it, produce the alternation that will
1465      * match all canonical equivalences of that sequence.
1466      */
1467     private String produceEquivalentAlternation(String source) {
1468         int len = countChars(source, 0, 1);
1469         if (source.length() == len)
1470             // source has one character.
1471             return source;
1472 
1473         String base = source.substring(0,len);
1474         String combiningMarks = source.substring(len);
1475 
1476         String[] perms = producePermutations(combiningMarks);
1477         StringBuilder result = new StringBuilder(source);
1478 
1479         // Add combined permutations
1480         for(int x=0; x<perms.length; x++) {
1481             String next = base + perms[x];
1482             if (x>0)
1483                 result.append("|"+next);
1484             next = composeOneStep(next);
1485             if (next != null)
1486                 result.append("|"+produceEquivalentAlternation(next));
1487         }
1488         return result.toString();
1489     }
1490 
1491     /**
1492      * Returns an array of strings that have all the possible
1493      * permutations of the characters in the input string.
1494      * This is used to get a list of all possible orderings
1495      * of a set of combining marks. Note that some of the permutations
1496      * are invalid because of combining class collisions, and these
1497      * possibilities must be removed because they are not canonically
1498      * equivalent.
1499      */
1500     private String[] producePermutations(String input) {
1501         if (input.length() == countChars(input, 0, 1))
1502             return new String[] {input};
1503 
1504         if (input.length() == countChars(input, 0, 2)) {
1505             int c0 = Character.codePointAt(input, 0);
1506             int c1 = Character.codePointAt(input, Character.charCount(c0));
1507             if (getClass(c1) == getClass(c0)) {
1508                 return new String[] {input};
1509             }
1510             String[] result = new String[2];
1511             result[0] = input;
1512             StringBuilder sb = new StringBuilder(2);
1513             sb.appendCodePoint(c1);
1514             sb.appendCodePoint(c0);
1515             result[1] = sb.toString();
1516             return result;
1517         }
1518 
1519         int length = 1;
1520         int nCodePoints = countCodePoints(input);
1521         for(int x=1; x<nCodePoints; x++)
1522             length = length * (x+1);
1523 
1524         String[] temp = new String[length];
1525 
1526         int combClass[] = new int[nCodePoints];
1527         for(int x=0, i=0; x<nCodePoints; x++) {
1528             int c = Character.codePointAt(input, i);
1529             combClass[x] = getClass(c);
1530             i +=  Character.charCount(c);
1531         }
1532 
1533         // For each char, take it out and add the permutations
1534         // of the remaining chars
1535         int index = 0;
1536         int len;
1537         // offset maintains the index in code units.
1538 loop:   for(int x=0, offset=0; x<nCodePoints; x++, offset+=len) {
1539             len = countChars(input, offset, 1);
1540             boolean skip = false;
1541             for(int y=x-1; y>=0; y--) {
1542                 if (combClass[y] == combClass[x]) {
1543                     continue loop;
1544                 }
1545             }
1546             StringBuilder sb = new StringBuilder(input);
1547             String otherChars = sb.delete(offset, offset+len).toString();
1548             String[] subResult = producePermutations(otherChars);
1549 
1550             String prefix = input.substring(offset, offset+len);
1551             for(int y=0; y<subResult.length; y++)
1552                 temp[index++] =  prefix + subResult[y];
1553         }
1554         String[] result = new String[index];
1555         for (int x=0; x<index; x++)
1556             result[x] = temp[x];
1557         return result;
1558     }
1559 
1560     private int getClass(int c) {
1561         return sun.text.Normalizer.getCombiningClass(c);
1562     }
1563 
1564     /**
1565      * Attempts to compose input by combining the first character
1566      * with the first combining mark following it. Returns a String
1567      * that is the composition of the leading character with its first
1568      * combining mark followed by the remaining combining marks. Returns
1569      * null if the first two characters cannot be further composed.
1570      */
1571     private String composeOneStep(String input) {
1572         int len = countChars(input, 0, 2);
1573         String firstTwoCharacters = input.substring(0, len);
1574         String result = Normalizer.normalize(firstTwoCharacters, Normalizer.Form.NFC);
1575 
1576         if (result.equals(firstTwoCharacters))
1577             return null;
1578         else {
1579             String remainder = input.substring(len);
1580             return result + remainder;
1581         }
1582     }
1583 
1584     /**
1585      * Preprocess any \Q...\E sequences in `temp', meta-quoting them.
1586      * See the description of `quotemeta' in perlfunc(1).
1587      */
1588     private void RemoveQEQuoting() {
1589         final int pLen = patternLength;
1590         int i = 0;
1591         while (i < pLen-1) {
1592             if (temp[i] != '\\')
1593                 i += 1;
1594             else if (temp[i + 1] != 'Q')
1595                 i += 2;
1596             else
1597                 break;
1598         }
1599         if (i >= pLen - 1)    // No \Q sequence found
1600             return;
1601         int j = i;
1602         i += 2;
1603         int[] newtemp = new int[j + 3*(pLen-i) + 2];
1604         System.arraycopy(temp, 0, newtemp, 0, j);
1605 
1606         boolean inQuote = true;
1607         boolean beginQuote = true;
1608         while (i < pLen) {
1609             int c = temp[i++];
1610             if (!ASCII.isAscii(c) || ASCII.isAlpha(c)) {
1611                 newtemp[j++] = c;
1612             } else if (ASCII.isDigit(c)) {
1613                 if (beginQuote) {
1614                     /*
1615                      * A unicode escape \[0xu] could be before this quote,
1616                      * and we don't want this numeric char to processed as
1617                      * part of the escape.
1618                      */
1619                     newtemp[j++] = '\\';
1620                     newtemp[j++] = 'x';
1621                     newtemp[j++] = '3';
1622                 }
1623                 newtemp[j++] = c;
1624             } else if (c != '\\') {
1625                 if (inQuote) newtemp[j++] = '\\';
1626                 newtemp[j++] = c;
1627             } else if (inQuote) {
1628                 if (temp[i] == 'E') {
1629                     i++;
1630                     inQuote = false;
1631                 } else {
1632                     newtemp[j++] = '\\';
1633                     newtemp[j++] = '\\';
1634                 }
1635             } else {
1636                 if (temp[i] == 'Q') {
1637                     i++;
1638                     inQuote = true;
1639                     beginQuote = true;
1640                     continue;
1641                 } else {
1642                     newtemp[j++] = c;
1643                     if (i != pLen)
1644                         newtemp[j++] = temp[i++];
1645                 }
1646             }
1647 
1648             beginQuote = false;
1649         }
1650 
1651         patternLength = j;
1652         temp = Arrays.copyOf(newtemp, j + 2); // double zero termination
1653     }
1654 
1655     /**
1656      * Copies regular expression to an int array and invokes the parsing
1657      * of the expression which will create the object tree.
1658      */
1659     private void compile() {
1660         // Handle canonical equivalences
1661         if (has(CANON_EQ) && !has(LITERAL)) {
1662             normalize();
1663         } else {
1664             normalizedPattern = pattern;
1665         }
1666         patternLength = normalizedPattern.length();
1667 
1668         // Copy pattern to int array for convenience
1669         // Use double zero to terminate pattern
1670         temp = new int[patternLength + 2];
1671 
1672         hasSupplementary = false;
1673         int c, count = 0;
1674         // Convert all chars into code points
1675         for (int x = 0; x < patternLength; x += Character.charCount(c)) {
1676             c = normalizedPattern.codePointAt(x);
1677             if (isSupplementary(c)) {
1678                 hasSupplementary = true;
1679             }
1680             temp[count++] = c;
1681         }
1682 
1683         patternLength = count;   // patternLength now in code points
1684 
1685         if (! has(LITERAL))
1686             RemoveQEQuoting();
1687 
1688         // Allocate all temporary objects here.
1689         buffer = new int[32];
1690         groupNodes = new GroupHead[10];
1691         namedGroups = null;
1692 
1693         if (has(LITERAL)) {
1694             // Literal pattern handling
1695             matchRoot = newSlice(temp, patternLength, hasSupplementary);
1696             matchRoot.next = lastAccept;
1697         } else {
1698             // Start recursive descent parsing
1699             matchRoot = expr(lastAccept);
1700             // Check extra pattern characters
1701             if (patternLength != cursor) {
1702                 if (peek() == ')') {
1703                     throw error("Unmatched closing ')'");
1704                 } else {
1705                     throw error("Unexpected internal error");
1706                 }
1707             }
1708         }
1709 
1710         // Peephole optimization
1711         if (matchRoot instanceof Slice) {
1712             root = BnM.optimize(matchRoot);
1713             if (root == matchRoot) {
1714                 root = hasSupplementary ? new StartS(matchRoot) : new Start(matchRoot);
1715             }
1716         } else if (matchRoot instanceof Begin || matchRoot instanceof First) {
1717             root = matchRoot;
1718         } else {
1719             root = hasSupplementary ? new StartS(matchRoot) : new Start(matchRoot);
1720         }
1721 
1722         // Release temporary storage
1723         temp = null;
1724         buffer = null;
1725         groupNodes = null;
1726         patternLength = 0;
1727         compiled = true;
1728     }
1729 
1730     Map<String, Integer> namedGroups() {
1731         if (namedGroups == null)
1732             namedGroups = new HashMap<>(2);
1733         return namedGroups;
1734     }
1735 
1736     /**
1737      * Used to print out a subtree of the Pattern to help with debugging.
1738      */
1739     private static void printObjectTree(Node node) {
1740         while(node != null) {
1741             if (node instanceof Prolog) {
1742                 System.out.println(node);
1743                 printObjectTree(((Prolog)node).loop);
1744                 System.out.println("**** end contents prolog loop");
1745             } else if (node instanceof Loop) {
1746                 System.out.println(node);
1747                 printObjectTree(((Loop)node).body);
1748                 System.out.println("**** end contents Loop body");
1749             } else if (node instanceof Curly) {
1750                 System.out.println(node);
1751                 printObjectTree(((Curly)node).atom);
1752                 System.out.println("**** end contents Curly body");
1753             } else if (node instanceof GroupCurly) {
1754                 System.out.println(node);
1755                 printObjectTree(((GroupCurly)node).atom);
1756                 System.out.println("**** end contents GroupCurly body");
1757             } else if (node instanceof GroupTail) {
1758                 System.out.println(node);
1759                 System.out.println("Tail next is "+node.next);
1760                 return;
1761             } else {
1762                 System.out.println(node);
1763             }
1764             node = node.next;
1765             if (node != null)
1766                 System.out.println("->next:");
1767             if (node == Pattern.accept) {
1768                 System.out.println("Accept Node");
1769                 node = null;
1770             }
1771        }
1772     }
1773 
1774     /**
1775      * Used to accumulate information about a subtree of the object graph
1776      * so that optimizations can be applied to the subtree.
1777      */
1778     static final class TreeInfo {
1779         int minLength;
1780         int maxLength;
1781         boolean maxValid;
1782         boolean deterministic;
1783 
1784         TreeInfo() {
1785             reset();
1786         }
1787         void reset() {
1788             minLength = 0;
1789             maxLength = 0;
1790             maxValid = true;
1791             deterministic = true;
1792         }
1793     }
1794 
1795     /*
1796      * The following private methods are mainly used to improve the
1797      * readability of the code. In order to let the Java compiler easily
1798      * inline them, we should not put many assertions or error checks in them.
1799      */
1800 
1801     /**
1802      * Indicates whether a particular flag is set or not.
1803      */
1804     private boolean has(int f) {
1805         return (flags & f) != 0;
1806     }
1807 
1808     /**
1809      * Match next character, signal error if failed.
1810      */
1811     private void accept(int ch, String s) {
1812         int testChar = temp[cursor++];
1813         if (has(COMMENTS))
1814             testChar = parsePastWhitespace(testChar);
1815         if (ch != testChar) {
1816             throw error(s);
1817         }
1818     }
1819 
1820     /**
1821      * Mark the end of pattern with a specific character.
1822      */
1823     private void mark(int c) {
1824         temp[patternLength] = c;
1825     }
1826 
1827     /**
1828      * Peek the next character, and do not advance the cursor.
1829      */
1830     private int peek() {
1831         int ch = temp[cursor];
1832         if (has(COMMENTS))
1833             ch = peekPastWhitespace(ch);
1834         return ch;
1835     }
1836 
1837     /**
1838      * Read the next character, and advance the cursor by one.
1839      */
1840     private int read() {
1841         int ch = temp[cursor++];
1842         if (has(COMMENTS))
1843             ch = parsePastWhitespace(ch);
1844         return ch;
1845     }
1846 
1847     /**
1848      * Read the next character, and advance the cursor by one,
1849      * ignoring the COMMENTS setting
1850      */
1851     private int readEscaped() {
1852         int ch = temp[cursor++];
1853         return ch;
1854     }
1855 
1856     /**
1857      * Advance the cursor by one, and peek the next character.
1858      */
1859     private int next() {
1860         int ch = temp[++cursor];
1861         if (has(COMMENTS))
1862             ch = peekPastWhitespace(ch);
1863         return ch;
1864     }
1865 
1866     /**
1867      * Advance the cursor by one, and peek the next character,
1868      * ignoring the COMMENTS setting
1869      */
1870     private int nextEscaped() {
1871         int ch = temp[++cursor];
1872         return ch;
1873     }
1874 
1875     /**
1876      * If in xmode peek past whitespace and comments.
1877      */
1878     private int peekPastWhitespace(int ch) {
1879         while (ASCII.isSpace(ch) || ch == '#') {
1880             while (ASCII.isSpace(ch))
1881                 ch = temp[++cursor];
1882             if (ch == '#') {
1883                 ch = peekPastLine();
1884             }
1885         }
1886         return ch;
1887     }
1888 
1889     /**
1890      * If in xmode parse past whitespace and comments.
1891      */
1892     private int parsePastWhitespace(int ch) {
1893         while (ASCII.isSpace(ch) || ch == '#') {
1894             while (ASCII.isSpace(ch))
1895                 ch = temp[cursor++];
1896             if (ch == '#')
1897                 ch = parsePastLine();
1898         }
1899         return ch;
1900     }
1901 
1902     /**
1903      * xmode parse past comment to end of line.
1904      */
1905     private int parsePastLine() {
1906         int ch = temp[cursor++];
1907         while (ch != 0 && !isLineSeparator(ch))
1908             ch = temp[cursor++];
1909         return ch;
1910     }
1911 
1912     /**
1913      * xmode peek past comment to end of line.
1914      */
1915     private int peekPastLine() {
1916         int ch = temp[++cursor];
1917         while (ch != 0 && !isLineSeparator(ch))
1918             ch = temp[++cursor];
1919         return ch;
1920     }
1921 
1922     /**
1923      * Determines if character is a line separator in the current mode
1924      */
1925     private boolean isLineSeparator(int ch) {
1926         if (has(UNIX_LINES)) {
1927             return ch == '\n';
1928         } else {
1929             return (ch == '\n' ||
1930                     ch == '\r' ||
1931                     (ch|1) == '\u2029' ||
1932                     ch == '\u0085');
1933         }
1934     }
1935 
1936     /**
1937      * Read the character after the next one, and advance the cursor by two.
1938      */
1939     private int skip() {
1940         int i = cursor;
1941         int ch = temp[i+1];
1942         cursor = i + 2;
1943         return ch;
1944     }
1945 
1946     /**
1947      * Unread one next character, and retreat cursor by one.
1948      */
1949     private void unread() {
1950         cursor--;
1951     }
1952 
1953     /**
1954      * Internal method used for handling all syntax errors. The pattern is
1955      * displayed with a pointer to aid in locating the syntax error.
1956      */
1957     private PatternSyntaxException error(String s) {
1958         return new PatternSyntaxException(s, normalizedPattern,  cursor - 1);
1959     }
1960 
1961     /**
1962      * Determines if there is any supplementary character or unpaired
1963      * surrogate in the specified range.
1964      */
1965     private boolean findSupplementary(int start, int end) {
1966         for (int i = start; i < end; i++) {
1967             if (isSupplementary(temp[i]))
1968                 return true;
1969         }
1970         return false;
1971     }
1972 
1973     /**
1974      * Determines if the specified code point is a supplementary
1975      * character or unpaired surrogate.
1976      */
1977     private static final boolean isSupplementary(int ch) {
1978         return ch >= Character.MIN_SUPPLEMENTARY_CODE_POINT ||
1979                Character.isSurrogate((char)ch);
1980     }
1981 
1982     /**
1983      *  The following methods handle the main parsing. They are sorted
1984      *  according to their precedence order, the lowest one first.
1985      */
1986 
1987     /**
1988      * The expression is parsed with branch nodes added for alternations.
1989      * This may be called recursively to parse sub expressions that may
1990      * contain alternations.
1991      */
1992     private Node expr(Node end) {
1993         Node prev = null;
1994         Node firstTail = null;
1995         Branch branch = null;
1996         Node branchConn = null;
1997 
1998         for (;;) {
1999             Node node = sequence(end);
2000             Node nodeTail = root;      //double return
2001             if (prev == null) {
2002                 prev = node;
2003                 firstTail = nodeTail;
2004             } else {
2005                 // Branch
2006                 if (branchConn == null) {
2007                     branchConn = new BranchConn();
2008                     branchConn.next = end;
2009                 }
2010                 if (node == end) {
2011                     // if the node returned from sequence() is "end"
2012                     // we have an empty expr, set a null atom into
2013                     // the branch to indicate to go "next" directly.
2014                     node = null;
2015                 } else {
2016                     // the "tail.next" of each atom goes to branchConn
2017                     nodeTail.next = branchConn;
2018                 }
2019                 if (prev == branch) {
2020                     branch.add(node);
2021                 } else {
2022                     if (prev == end) {
2023                         prev = null;
2024                     } else {
2025                         // replace the "end" with "branchConn" at its tail.next
2026                         // when put the "prev" into the branch as the first atom.
2027                         firstTail.next = branchConn;
2028                     }
2029                     prev = branch = new Branch(prev, node, branchConn);
2030                 }
2031             }
2032             if (peek() != '|') {
2033                 return prev;
2034             }
2035             next();
2036         }
2037     }
2038 
2039     @SuppressWarnings("fallthrough")
2040     /**
2041      * Parsing of sequences between alternations.
2042      */
2043     private Node sequence(Node end) {
2044         Node head = null;
2045         Node tail = null;
2046         Node node = null;
2047     LOOP:
2048         for (;;) {
2049             int ch = peek();
2050             switch (ch) {
2051             case '(':
2052                 // Because group handles its own closure,
2053                 // we need to treat it differently
2054                 node = group0();
2055                 // Check for comment or flag group
2056                 if (node == null)
2057                     continue;
2058                 if (head == null)
2059                     head = node;
2060                 else
2061                     tail.next = node;
2062                 // Double return: Tail was returned in root
2063                 tail = root;
2064                 continue;
2065             case '[':
2066                 node = clazz(true);
2067                 break;
2068             case '\\':
2069                 ch = nextEscaped();
2070                 if (ch == 'p' || ch == 'P') {
2071                     boolean oneLetter = true;
2072                     boolean comp = (ch == 'P');
2073                     ch = next(); // Consume { if present
2074                     if (ch != '{') {
2075                         unread();
2076                     } else {
2077                         oneLetter = false;
2078                     }
2079                     node = family(oneLetter, comp);
2080                 } else {
2081                     unread();
2082                     node = atom();
2083                 }
2084                 break;
2085             case '^':
2086                 next();
2087                 if (has(MULTILINE)) {
2088                     if (has(UNIX_LINES))
2089                         node = new UnixCaret();
2090                     else
2091                         node = new Caret();
2092                 } else {
2093                     node = new Begin();
2094                 }
2095                 break;
2096             case '$':
2097                 next();
2098                 if (has(UNIX_LINES))
2099                     node = new UnixDollar(has(MULTILINE));
2100                 else
2101                     node = new Dollar(has(MULTILINE));
2102                 break;
2103             case '.':
2104                 next();
2105                 if (has(DOTALL)) {
2106                     node = new All();
2107                 } else {
2108                     if (has(UNIX_LINES))
2109                         node = new UnixDot();
2110                     else {
2111                         node = new Dot();
2112                     }
2113                 }
2114                 break;
2115             case '|':
2116             case ')':
2117                 break LOOP;
2118             case ']': // Now interpreting dangling ] and } as literals
2119             case '}':
2120                 node = atom();
2121                 break;
2122             case '?':
2123             case '*':
2124             case '+':
2125                 next();
2126                 throw error("Dangling meta character '" + ((char)ch) + "'");
2127             case 0:
2128                 if (cursor >= patternLength) {
2129                     break LOOP;
2130                 }
2131                 // Fall through
2132             default:
2133                 node = atom();
2134                 break;
2135             }
2136 
2137             node = closure(node);
2138 
2139             if (head == null) {
2140                 head = tail = node;
2141             } else {
2142                 tail.next = node;
2143                 tail = node;
2144             }
2145         }
2146         if (head == null) {
2147             return end;
2148         }
2149         tail.next = end;
2150         root = tail;      //double return
2151         return head;
2152     }
2153 
2154     @SuppressWarnings("fallthrough")
2155     /**
2156      * Parse and add a new Single or Slice.
2157      */
2158     private Node atom() {
2159         int first = 0;
2160         int prev = -1;
2161         boolean hasSupplementary = false;
2162         int ch = peek();
2163         for (;;) {
2164             switch (ch) {
2165             case '*':
2166             case '+':
2167             case '?':
2168             case '{':
2169                 if (first > 1) {
2170                     cursor = prev;    // Unwind one character
2171                     first--;
2172                 }
2173                 break;
2174             case '$':
2175             case '.':
2176             case '^':
2177             case '(':
2178             case '[':
2179             case '|':
2180             case ')':
2181                 break;
2182             case '\\':
2183                 ch = nextEscaped();
2184                 if (ch == 'p' || ch == 'P') { // Property
2185                     if (first > 0) { // Slice is waiting; handle it first
2186                         unread();
2187                         break;
2188                     } else { // No slice; just return the family node
2189                         boolean comp = (ch == 'P');
2190                         boolean oneLetter = true;
2191                         ch = next(); // Consume { if present
2192                         if (ch != '{')
2193                             unread();
2194                         else
2195                             oneLetter = false;
2196                         return family(oneLetter, comp);
2197                     }
2198                 }
2199                 unread();
2200                 prev = cursor;
2201                 ch = escape(false, first == 0, false);
2202                 if (ch >= 0) {
2203                     append(ch, first);
2204                     first++;
2205                     if (isSupplementary(ch)) {
2206                         hasSupplementary = true;
2207                     }
2208                     ch = peek();
2209                     continue;
2210                 } else if (first == 0) {
2211                     return root;
2212                 }
2213                 // Unwind meta escape sequence
2214                 cursor = prev;
2215                 break;
2216             case 0:
2217                 if (cursor >= patternLength) {
2218                     break;
2219                 }
2220                 // Fall through
2221             default:
2222                 prev = cursor;
2223                 append(ch, first);
2224                 first++;
2225                 if (isSupplementary(ch)) {
2226                     hasSupplementary = true;
2227                 }
2228                 ch = next();
2229                 continue;
2230             }
2231             break;
2232         }
2233         if (first == 1) {
2234             return newSingle(buffer[0]);
2235         } else {
2236             return newSlice(buffer, first, hasSupplementary);
2237         }
2238     }
2239 
2240     private void append(int ch, int len) {
2241         if (len >= buffer.length) {
2242             int[] tmp = new int[len+len];
2243             System.arraycopy(buffer, 0, tmp, 0, len);
2244             buffer = tmp;
2245         }
2246         buffer[len] = ch;
2247     }
2248 
2249     /**
2250      * Parses a backref greedily, taking as many numbers as it
2251      * can. The first digit is always treated as a backref, but
2252      * multi digit numbers are only treated as a backref if at
2253      * least that many backrefs exist at this point in the regex.
2254      */
2255     private Node ref(int refNum) {
2256         boolean done = false;
2257         while(!done) {
2258             int ch = peek();
2259             switch(ch) {
2260             case '0':
2261             case '1':
2262             case '2':
2263             case '3':
2264             case '4':
2265             case '5':
2266             case '6':
2267             case '7':
2268             case '8':
2269             case '9':
2270                 int newRefNum = (refNum * 10) + (ch - '0');
2271                 // Add another number if it doesn't make a group
2272                 // that doesn't exist
2273                 if (capturingGroupCount - 1 < newRefNum) {
2274                     done = true;
2275                     break;
2276                 }
2277                 refNum = newRefNum;
2278                 read();
2279                 break;
2280             default:
2281                 done = true;
2282                 break;
2283             }
2284         }
2285         if (has(CASE_INSENSITIVE))
2286             return new CIBackRef(refNum, has(UNICODE_CASE));
2287         else
2288             return new BackRef(refNum);
2289     }
2290 
2291     /**
2292      * Parses an escape sequence to determine the actual value that needs
2293      * to be matched.
2294      * If -1 is returned and create was true a new object was added to the tree
2295      * to handle the escape sequence.
2296      * If the returned value is greater than zero, it is the value that
2297      * matches the escape sequence.
2298      */
2299     private int escape(boolean inclass, boolean create, boolean isrange) {
2300         int ch = skip();
2301         switch (ch) {
2302         case '0':
2303             return o();
2304         case '1':
2305         case '2':
2306         case '3':
2307         case '4':
2308         case '5':
2309         case '6':
2310         case '7':
2311         case '8':
2312         case '9':
2313             if (inclass) break;
2314             if (create) {
2315                 root = ref((ch - '0'));
2316             }
2317             return -1;
2318         case 'A':
2319             if (inclass) break;
2320             if (create) root = new Begin();
2321             return -1;
2322         case 'B':
2323             if (inclass) break;
2324             if (create) root = new Bound(Bound.NONE, has(UNICODE_CHARACTER_CLASS));
2325             return -1;
2326         case 'C':
2327             break;
2328         case 'D':
2329             if (create) root = has(UNICODE_CHARACTER_CLASS)
2330                                ? new Utype(UnicodeProp.DIGIT).complement()
2331                                : new Ctype(ASCII.DIGIT).complement();
2332             return -1;
2333         case 'E':
2334         case 'F':
2335             break;
2336         case 'G':
2337             if (inclass) break;
2338             if (create) root = new LastMatch();
2339             return -1;
2340         case 'H':
2341             if (create) root = new HorizWS().complement();
2342             return -1;
2343         case 'I':
2344         case 'J':
2345         case 'K':
2346         case 'L':
2347         case 'M':
2348         case 'N':
2349         case 'O':
2350         case 'P':
2351         case 'Q':
2352             break;
2353         case 'R':
2354             if (inclass) break;
2355             if (create) root = new LineEnding();
2356             return -1;
2357         case 'S':
2358             if (create) root = has(UNICODE_CHARACTER_CLASS)
2359                                ? new Utype(UnicodeProp.WHITE_SPACE).complement()
2360                                : new Ctype(ASCII.SPACE).complement();
2361             return -1;
2362         case 'T':
2363         case 'U':
2364             break;
2365         case 'V':
2366             if (create) root = new VertWS().complement();
2367             return -1;
2368         case 'W':
2369             if (create) root = has(UNICODE_CHARACTER_CLASS)
2370                                ? new Utype(UnicodeProp.WORD).complement()
2371                                : new Ctype(ASCII.WORD).complement();
2372             return -1;
2373         case 'X':
2374         case 'Y':
2375             break;
2376         case 'Z':
2377             if (inclass) break;
2378             if (create) {
2379                 if (has(UNIX_LINES))
2380                     root = new UnixDollar(false);
2381                 else
2382                     root = new Dollar(false);
2383             }
2384             return -1;
2385         case 'a':
2386             return '\007';
2387         case 'b':
2388             if (inclass) break;
2389             if (create) root = new Bound(Bound.BOTH, has(UNICODE_CHARACTER_CLASS));
2390             return -1;
2391         case 'c':
2392             return c();
2393         case 'd':
2394             if (create) root = has(UNICODE_CHARACTER_CLASS)
2395                                ? new Utype(UnicodeProp.DIGIT)
2396                                : new Ctype(ASCII.DIGIT);
2397             return -1;
2398         case 'e':
2399             return '\033';
2400         case 'f':
2401             return '\f';
2402         case 'g':
2403             break;
2404         case 'h':
2405             if (create) root = new HorizWS();
2406             return -1;
2407         case 'i':
2408         case 'j':
2409             break;
2410         case 'k':
2411             if (inclass)
2412                 break;
2413             if (read() != '<')
2414                 throw error("\\k is not followed by '<' for named capturing group");
2415             String name = groupname(read());
2416             if (!namedGroups().containsKey(name))
2417                 throw error("(named capturing group <"+ name+"> does not exit");
2418             if (create) {
2419                 if (has(CASE_INSENSITIVE))
2420                     root = new CIBackRef(namedGroups().get(name), has(UNICODE_CASE));
2421                 else
2422                     root = new BackRef(namedGroups().get(name));
2423             }
2424             return -1;
2425         case 'l':
2426         case 'm':
2427             break;
2428         case 'n':
2429             return '\n';
2430         case 'o':
2431         case 'p':
2432         case 'q':
2433             break;
2434         case 'r':
2435             return '\r';
2436         case 's':
2437             if (create) root = has(UNICODE_CHARACTER_CLASS)
2438                                ? new Utype(UnicodeProp.WHITE_SPACE)
2439                                : new Ctype(ASCII.SPACE);
2440             return -1;
2441         case 't':
2442             return '\t';
2443         case 'u':
2444             return u();
2445         case 'v':
2446             // '\v' was implemented as VT/0x0B in releases < 1.8 (though
2447             // undocumented). In JDK8 '\v' is specified as a predefined
2448             // character class for all vertical whitespace characters.
2449             // So [-1, root=VertWS node] pair is returned (instead of a
2450             // single 0x0B). This breaks the range if '\v' is used as
2451             // the start or end value, such as [\v-...] or [...-\v], in
2452             // which a single definite value (0x0B) is expected. For
2453             // compatibility concern '\013'/0x0B is returned if isrange.
2454             if (isrange)
2455                 return '\013';
2456             if (create) root = new VertWS();
2457             return -1;
2458         case 'w':
2459             if (create) root = has(UNICODE_CHARACTER_CLASS)
2460                                ? new Utype(UnicodeProp.WORD)
2461                                : new Ctype(ASCII.WORD);
2462             return -1;
2463         case 'x':
2464             return x();
2465         case 'y':
2466             break;
2467         case 'z':
2468             if (inclass) break;
2469             if (create) root = new End();
2470             return -1;
2471         default:
2472             return ch;
2473         }
2474         throw error("Illegal/unsupported escape sequence");
2475     }
2476 
2477     /**
2478      * Parse a character class, and return the node that matches it.
2479      *
2480      * Consumes a ] on the way out if consume is true. Usually consume
2481      * is true except for the case of [abc&&def] where def is a separate
2482      * right hand node with "understood" brackets.
2483      */
2484     private CharProperty clazz(boolean consume) {
2485         CharProperty prev = null;
2486         CharProperty node = null;
2487         BitClass bits = new BitClass();
2488         boolean include = true;
2489         boolean firstInClass = true;
2490         int ch = next();
2491         for (;;) {
2492             switch (ch) {
2493                 case '^':
2494                     // Negates if first char in a class, otherwise literal
2495                     if (firstInClass) {
2496                         if (temp[cursor-1] != '[')
2497                             break;
2498                         ch = next();
2499                         include = !include;
2500                         continue;
2501                     } else {
2502                         // ^ not first in class, treat as literal
2503                         break;
2504                     }
2505                 case '[':
2506                     firstInClass = false;
2507                     node = clazz(true);
2508                     if (prev == null)
2509                         prev = node;
2510                     else
2511                         prev = union(prev, node);
2512                     ch = peek();
2513                     continue;
2514                 case '&':
2515                     firstInClass = false;
2516                     ch = next();
2517                     if (ch == '&') {
2518                         ch = next();
2519                         CharProperty rightNode = null;
2520                         while (ch != ']' && ch != '&') {
2521                             if (ch == '[') {
2522                                 if (rightNode == null)
2523                                     rightNode = clazz(true);
2524                                 else
2525                                     rightNode = union(rightNode, clazz(true));
2526                             } else { // abc&&def
2527                                 unread();
2528                                 rightNode = clazz(false);
2529                             }
2530                             ch = peek();
2531                         }
2532                         if (rightNode != null)
2533                             node = rightNode;
2534                         if (prev == null) {
2535                             if (rightNode == null)
2536                                 throw error("Bad class syntax");
2537                             else
2538                                 prev = rightNode;
2539                         } else {
2540                             prev = intersection(prev, node);
2541                         }
2542                     } else {
2543                         // treat as a literal &
2544                         unread();
2545                         break;
2546                     }
2547                     continue;
2548                 case 0:
2549                     firstInClass = false;
2550                     if (cursor >= patternLength)
2551                         throw error("Unclosed character class");
2552                     break;
2553                 case ']':
2554                     firstInClass = false;
2555                     if (prev != null) {
2556                         if (consume)
2557                             next();
2558                         return prev;
2559                     }
2560                     break;
2561                 default:
2562                     firstInClass = false;
2563                     break;
2564             }
2565             node = range(bits);
2566             if (include) {
2567                 if (prev == null) {
2568                     prev = node;
2569                 } else {
2570                     if (prev != node)
2571                         prev = union(prev, node);
2572                 }
2573             } else {
2574                 if (prev == null) {
2575                     prev = node.complement();
2576                 } else {
2577                     if (prev != node)
2578                         prev = setDifference(prev, node);
2579                 }
2580             }
2581             ch = peek();
2582         }
2583     }
2584 
2585     private CharProperty bitsOrSingle(BitClass bits, int ch) {
2586         /* Bits can only handle codepoints in [u+0000-u+00ff] range.
2587            Use "single" node instead of bits when dealing with unicode
2588            case folding for codepoints listed below.
2589            (1)Uppercase out of range: u+00ff, u+00b5
2590               toUpperCase(u+00ff) -> u+0178
2591               toUpperCase(u+00b5) -> u+039c
2592            (2)LatinSmallLetterLongS u+17f
2593               toUpperCase(u+017f) -> u+0053
2594            (3)LatinSmallLetterDotlessI u+131
2595               toUpperCase(u+0131) -> u+0049
2596            (4)LatinCapitalLetterIWithDotAbove u+0130
2597               toLowerCase(u+0130) -> u+0069
2598            (5)KelvinSign u+212a
2599               toLowerCase(u+212a) ==> u+006B
2600            (6)AngstromSign u+212b
2601               toLowerCase(u+212b) ==> u+00e5
2602         */
2603         int d;
2604         if (ch < 256 &&
2605             !(has(CASE_INSENSITIVE) && has(UNICODE_CASE) &&
2606               (ch == 0xff || ch == 0xb5 ||
2607                ch == 0x49 || ch == 0x69 ||  //I and i
2608                ch == 0x53 || ch == 0x73 ||  //S and s
2609                ch == 0x4b || ch == 0x6b ||  //K and k
2610                ch == 0xc5 || ch == 0xe5)))  //A+ring
2611             return bits.add(ch, flags());
2612         return newSingle(ch);
2613     }
2614 
2615     /**
2616      * Parse a single character or a character range in a character class
2617      * and return its representative node.
2618      */
2619     private CharProperty range(BitClass bits) {
2620         int ch = peek();
2621         if (ch == '\\') {
2622             ch = nextEscaped();
2623             if (ch == 'p' || ch == 'P') { // A property
2624                 boolean comp = (ch == 'P');
2625                 boolean oneLetter = true;
2626                 // Consume { if present
2627                 ch = next();
2628                 if (ch != '{')
2629                     unread();
2630                 else
2631                     oneLetter = false;
2632                 return family(oneLetter, comp);
2633             } else { // ordinary escape
2634                 boolean isrange = temp[cursor+1] == '-';
2635                 unread();
2636                 ch = escape(true, true, isrange);
2637                 if (ch == -1)
2638                     return (CharProperty) root;
2639             }
2640         } else {
2641             next();
2642         }
2643         if (ch >= 0) {
2644             if (peek() == '-') {
2645                 int endRange = temp[cursor+1];
2646                 if (endRange == '[') {
2647                     return bitsOrSingle(bits, ch);
2648                 }
2649                 if (endRange != ']') {
2650                     next();
2651                     int m = peek();
2652                     if (m == '\\') {
2653                         m = escape(true, false, true);
2654                     } else {
2655                         next();
2656                     }
2657                     if (m < ch) {
2658                         throw error("Illegal character range");
2659                     }
2660                     if (has(CASE_INSENSITIVE))
2661                         return caseInsensitiveRangeFor(ch, m);
2662                     else
2663                         return rangeFor(ch, m);
2664                 }
2665             }
2666             return bitsOrSingle(bits, ch);
2667         }
2668         throw error("Unexpected character '"+((char)ch)+"'");
2669     }
2670 
2671     /**
2672      * Parses a Unicode character family and returns its representative node.
2673      */
2674     private CharProperty family(boolean singleLetter,
2675                                 boolean maybeComplement)
2676     {
2677         next();
2678         String name;
2679         CharProperty node = null;
2680 
2681         if (singleLetter) {
2682             int c = temp[cursor];
2683             if (!Character.isSupplementaryCodePoint(c)) {
2684                 name = String.valueOf((char)c);
2685             } else {
2686                 name = new String(temp, cursor, 1);
2687             }
2688             read();
2689         } else {
2690             int i = cursor;
2691             mark('}');
2692             while(read() != '}') {
2693             }
2694             mark('\000');
2695             int j = cursor;
2696             if (j > patternLength)
2697                 throw error("Unclosed character family");
2698             if (i + 1 >= j)
2699                 throw error("Empty character family");
2700             name = new String(temp, i, j-i-1);
2701         }
2702 
2703         int i = name.indexOf('=');
2704         if (i != -1) {
2705             // property construct \p{name=value}
2706             String value = name.substring(i + 1);
2707             name = name.substring(0, i).toLowerCase(Locale.ENGLISH);
2708             if ("sc".equals(name) || "script".equals(name)) {
2709                 node = unicodeScriptPropertyFor(value);
2710             } else if ("blk".equals(name) || "block".equals(name)) {
2711                 node = unicodeBlockPropertyFor(value);
2712             } else if ("gc".equals(name) || "general_category".equals(name)) {
2713                 node = charPropertyNodeFor(value);
2714             } else {
2715                 throw error("Unknown Unicode property {name=<" + name + ">, "
2716                              + "value=<" + value + ">}");
2717             }
2718         } else {
2719             if (name.startsWith("In")) {
2720                 // \p{inBlockName}
2721                 node = unicodeBlockPropertyFor(name.substring(2));
2722             } else if (name.startsWith("Is")) {
2723                 // \p{isGeneralCategory} and \p{isScriptName}
2724                 name = name.substring(2);
2725                 UnicodeProp uprop = UnicodeProp.forName(name);
2726                 if (uprop != null)
2727                     node = new Utype(uprop);
2728                 if (node == null)
2729                     node = CharPropertyNames.charPropertyFor(name);
2730                 if (node == null)
2731                     node = unicodeScriptPropertyFor(name);
2732             } else {
2733                 if (has(UNICODE_CHARACTER_CLASS)) {
2734                     UnicodeProp uprop = UnicodeProp.forPOSIXName(name);
2735                     if (uprop != null)
2736                         node = new Utype(uprop);
2737                 }
2738                 if (node == null)
2739                     node = charPropertyNodeFor(name);
2740             }
2741         }
2742         if (maybeComplement) {
2743             if (node instanceof Category || node instanceof Block)
2744                 hasSupplementary = true;
2745             node = node.complement();
2746         }
2747         return node;
2748     }
2749 
2750 
2751     /**
2752      * Returns a CharProperty matching all characters belong to
2753      * a UnicodeScript.
2754      */
2755     private CharProperty unicodeScriptPropertyFor(String name) {
2756         final Character.UnicodeScript script;
2757         try {
2758             script = Character.UnicodeScript.forName(name);
2759         } catch (IllegalArgumentException iae) {
2760             throw error("Unknown character script name {" + name + "}");
2761         }
2762         return new Script(script);
2763     }
2764 
2765     /**
2766      * Returns a CharProperty matching all characters in a UnicodeBlock.
2767      */
2768     private CharProperty unicodeBlockPropertyFor(String name) {
2769         final Character.UnicodeBlock block;
2770         try {
2771             block = Character.UnicodeBlock.forName(name);
2772         } catch (IllegalArgumentException iae) {
2773             throw error("Unknown character block name {" + name + "}");
2774         }
2775         return new Block(block);
2776     }
2777 
2778     /**
2779      * Returns a CharProperty matching all characters in a named property.
2780      */
2781     private CharProperty charPropertyNodeFor(String name) {
2782         CharProperty p = CharPropertyNames.charPropertyFor(name);
2783         if (p == null)
2784             throw error("Unknown character property name {" + name + "}");
2785         return p;
2786     }
2787 
2788     /**
2789      * Parses and returns the name of a "named capturing group", the trailing
2790      * ">" is consumed after parsing.
2791      */
2792     private String groupname(int ch) {
2793         StringBuilder sb = new StringBuilder();
2794         sb.append(Character.toChars(ch));
2795         while (ASCII.isLower(ch=read()) || ASCII.isUpper(ch) ||
2796                ASCII.isDigit(ch)) {
2797             sb.append(Character.toChars(ch));
2798         }
2799         if (sb.length() == 0)
2800             throw error("named capturing group has 0 length name");
2801         if (ch != '>')
2802             throw error("named capturing group is missing trailing '>'");
2803         return sb.toString();
2804     }
2805 
2806     /**
2807      * Parses a group and returns the head node of a set of nodes that process
2808      * the group. Sometimes a double return system is used where the tail is
2809      * returned in root.
2810      */
2811     private Node group0() {
2812         boolean capturingGroup = false;
2813         Node head = null;
2814         Node tail = null;
2815         int save = flags;
2816         root = null;
2817         int ch = next();
2818         if (ch == '?') {
2819             ch = skip();
2820             switch (ch) {
2821             case ':':   //  (?:xxx) pure group
2822                 head = createGroup(true);
2823                 tail = root;
2824                 head.next = expr(tail);
2825                 break;
2826             case '=':   // (?=xxx) and (?!xxx) lookahead
2827             case '!':
2828                 head = createGroup(true);
2829                 tail = root;
2830                 head.next = expr(tail);
2831                 if (ch == '=') {
2832                     head = tail = new Pos(head);
2833                 } else {
2834                     head = tail = new Neg(head);
2835                 }
2836                 break;
2837             case '>':   // (?>xxx)  independent group
2838                 head = createGroup(true);
2839                 tail = root;
2840                 head.next = expr(tail);
2841                 head = tail = new Ques(head, INDEPENDENT);
2842                 break;
2843             case '<':   // (?<xxx)  look behind
2844                 ch = read();
2845                 if (ASCII.isLower(ch) || ASCII.isUpper(ch)) {
2846                     // named captured group
2847                     String name = groupname(ch);
2848                     if (namedGroups().containsKey(name))
2849                         throw error("Named capturing group <" + name
2850                                     + "> is already defined");
2851                     capturingGroup = true;
2852                     head = createGroup(false);
2853                     tail = root;
2854                     namedGroups().put(name, capturingGroupCount-1);
2855                     head.next = expr(tail);
2856                     break;
2857                 }
2858                 int start = cursor;
2859                 head = createGroup(true);
2860                 tail = root;
2861                 head.next = expr(tail);
2862                 tail.next = lookbehindEnd;
2863                 TreeInfo info = new TreeInfo();
2864                 head.study(info);
2865                 if (info.maxValid == false) {
2866                     throw error("Look-behind group does not have "
2867                                 + "an obvious maximum length");
2868                 }
2869                 boolean hasSupplementary = findSupplementary(start, patternLength);
2870                 if (ch == '=') {
2871                     head = tail = (hasSupplementary ?
2872                                    new BehindS(head, info.maxLength,
2873                                                info.minLength) :
2874                                    new Behind(head, info.maxLength,
2875                                               info.minLength));
2876                 } else if (ch == '!') {
2877                     head = tail = (hasSupplementary ?
2878                                    new NotBehindS(head, info.maxLength,
2879                                                   info.minLength) :
2880                                    new NotBehind(head, info.maxLength,
2881                                                  info.minLength));
2882                 } else {
2883                     throw error("Unknown look-behind group");
2884                 }
2885                 break;
2886             case '$':
2887             case '@':
2888                 throw error("Unknown group type");
2889             default:    // (?xxx:) inlined match flags
2890                 unread();
2891                 addFlag();
2892                 ch = read();
2893                 if (ch == ')') {
2894                     return null;    // Inline modifier only
2895                 }
2896                 if (ch != ':') {
2897                     throw error("Unknown inline modifier");
2898                 }
2899                 head = createGroup(true);
2900                 tail = root;
2901                 head.next = expr(tail);
2902                 break;
2903             }
2904         } else { // (xxx) a regular group
2905             capturingGroup = true;
2906             head = createGroup(false);
2907             tail = root;
2908             head.next = expr(tail);
2909         }
2910 
2911         accept(')', "Unclosed group");
2912         flags = save;
2913 
2914         // Check for quantifiers
2915         Node node = closure(head);
2916         if (node == head) { // No closure
2917             root = tail;
2918             return node;    // Dual return
2919         }
2920         if (head == tail) { // Zero length assertion
2921             root = node;
2922             return node;    // Dual return
2923         }
2924 
2925         if (node instanceof Ques) {
2926             Ques ques = (Ques) node;
2927             if (ques.type == POSSESSIVE) {
2928                 root = node;
2929                 return node;
2930             }
2931             tail.next = new BranchConn();
2932             tail = tail.next;
2933             if (ques.type == GREEDY) {
2934                 head = new Branch(head, null, tail);
2935             } else { // Reluctant quantifier
2936                 head = new Branch(null, head, tail);
2937             }
2938             root = tail;
2939             return head;
2940         } else if (node instanceof Curly) {
2941             Curly curly = (Curly) node;
2942             if (curly.type == POSSESSIVE) {
2943                 root = node;
2944                 return node;
2945             }
2946             // Discover if the group is deterministic
2947             TreeInfo info = new TreeInfo();
2948             if (head.study(info)) { // Deterministic
2949                 GroupTail temp = (GroupTail) tail;
2950                 head = root = new GroupCurly(head.next, curly.cmin,
2951                                    curly.cmax, curly.type,
2952                                    ((GroupTail)tail).localIndex,
2953                                    ((GroupTail)tail).groupIndex,
2954                                              capturingGroup);
2955                 return head;
2956             } else { // Non-deterministic
2957                 int temp = ((GroupHead) head).localIndex;
2958                 Loop loop;
2959                 if (curly.type == GREEDY)
2960                     loop = new Loop(this.localCount, temp);
2961                 else  // Reluctant Curly
2962                     loop = new LazyLoop(this.localCount, temp);
2963                 Prolog prolog = new Prolog(loop);
2964                 this.localCount += 1;
2965                 loop.cmin = curly.cmin;
2966                 loop.cmax = curly.cmax;
2967                 loop.body = head;
2968                 tail.next = loop;
2969                 root = loop;
2970                 return prolog; // Dual return
2971             }
2972         }
2973         throw error("Internal logic error");
2974     }
2975 
2976     /**
2977      * Create group head and tail nodes using double return. If the group is
2978      * created with anonymous true then it is a pure group and should not
2979      * affect group counting.
2980      */
2981     private Node createGroup(boolean anonymous) {
2982         int localIndex = localCount++;
2983         int groupIndex = 0;
2984         if (!anonymous)
2985             groupIndex = capturingGroupCount++;
2986         GroupHead head = new GroupHead(localIndex);
2987         root = new GroupTail(localIndex, groupIndex);
2988         if (!anonymous && groupIndex < 10)
2989             groupNodes[groupIndex] = head;
2990         return head;
2991     }
2992 
2993     @SuppressWarnings("fallthrough")
2994     /**
2995      * Parses inlined match flags and set them appropriately.
2996      */
2997     private void addFlag() {
2998         int ch = peek();
2999         for (;;) {
3000             switch (ch) {
3001             case 'i':
3002                 flags |= CASE_INSENSITIVE;
3003                 break;
3004             case 'm':
3005                 flags |= MULTILINE;
3006                 break;
3007             case 's':
3008                 flags |= DOTALL;
3009                 break;
3010             case 'd':
3011                 flags |= UNIX_LINES;
3012                 break;
3013             case 'u':
3014                 flags |= UNICODE_CASE;
3015                 break;
3016             case 'c':
3017                 flags |= CANON_EQ;
3018                 break;
3019             case 'x':
3020                 flags |= COMMENTS;
3021                 break;
3022             case 'U':
3023                 flags |= (UNICODE_CHARACTER_CLASS | UNICODE_CASE);
3024                 break;
3025             case '-': // subFlag then fall through
3026                 ch = next();
3027                 subFlag();
3028             default:
3029                 return;
3030             }
3031             ch = next();
3032         }
3033     }
3034 
3035     @SuppressWarnings("fallthrough")
3036     /**
3037      * Parses the second part of inlined match flags and turns off
3038      * flags appropriately.
3039      */
3040     private void subFlag() {
3041         int ch = peek();
3042         for (;;) {
3043             switch (ch) {
3044             case 'i':
3045                 flags &= ~CASE_INSENSITIVE;
3046                 break;
3047             case 'm':
3048                 flags &= ~MULTILINE;
3049                 break;
3050             case 's':
3051                 flags &= ~DOTALL;
3052                 break;
3053             case 'd':
3054                 flags &= ~UNIX_LINES;
3055                 break;
3056             case 'u':
3057                 flags &= ~UNICODE_CASE;
3058                 break;
3059             case 'c':
3060                 flags &= ~CANON_EQ;
3061                 break;
3062             case 'x':
3063                 flags &= ~COMMENTS;
3064                 break;
3065             case 'U':
3066                 flags &= ~(UNICODE_CHARACTER_CLASS | UNICODE_CASE);
3067             default:
3068                 return;
3069             }
3070             ch = next();
3071         }
3072     }
3073 
3074     static final int MAX_REPS   = 0x7FFFFFFF;
3075 
3076     static final int GREEDY     = 0;
3077 
3078     static final int LAZY       = 1;
3079 
3080     static final int POSSESSIVE = 2;
3081 
3082     static final int INDEPENDENT = 3;
3083 
3084     /**
3085      * Processes repetition. If the next character peeked is a quantifier
3086      * then new nodes must be appended to handle the repetition.
3087      * Prev could be a single or a group, so it could be a chain of nodes.
3088      */
3089     private Node closure(Node prev) {
3090         Node atom;
3091         int ch = peek();
3092         switch (ch) {
3093         case '?':
3094             ch = next();
3095             if (ch == '?') {
3096                 next();
3097                 return new Ques(prev, LAZY);
3098             } else if (ch == '+') {
3099                 next();
3100                 return new Ques(prev, POSSESSIVE);
3101             }
3102             return new Ques(prev, GREEDY);
3103         case '*':
3104             ch = next();
3105             if (ch == '?') {
3106                 next();
3107                 return new Curly(prev, 0, MAX_REPS, LAZY);
3108             } else if (ch == '+') {
3109                 next();
3110                 return new Curly(prev, 0, MAX_REPS, POSSESSIVE);
3111             }
3112             return new Curly(prev, 0, MAX_REPS, GREEDY);
3113         case '+':
3114             ch = next();
3115             if (ch == '?') {
3116                 next();
3117                 return new Curly(prev, 1, MAX_REPS, LAZY);
3118             } else if (ch == '+') {
3119                 next();
3120                 return new Curly(prev, 1, MAX_REPS, POSSESSIVE);
3121             }
3122             return new Curly(prev, 1, MAX_REPS, GREEDY);
3123         case '{':
3124             ch = temp[cursor+1];
3125             if (ASCII.isDigit(ch)) {
3126                 skip();
3127                 int cmin = 0;
3128                 do {
3129                     cmin = cmin * 10 + (ch - '0');
3130                 } while (ASCII.isDigit(ch = read()));
3131                 int cmax = cmin;
3132                 if (ch == ',') {
3133                     ch = read();
3134                     cmax = MAX_REPS;
3135                     if (ch != '}') {
3136                         cmax = 0;
3137                         while (ASCII.isDigit(ch)) {
3138                             cmax = cmax * 10 + (ch - '0');
3139                             ch = read();
3140                         }
3141                     }
3142                 }
3143                 if (ch != '}')
3144                     throw error("Unclosed counted closure");
3145                 if (((cmin) | (cmax) | (cmax - cmin)) < 0)
3146                     throw error("Illegal repetition range");
3147                 Curly curly;
3148                 ch = peek();
3149                 if (ch == '?') {
3150                     next();
3151                     curly = new Curly(prev, cmin, cmax, LAZY);
3152                 } else if (ch == '+') {
3153                     next();
3154                     curly = new Curly(prev, cmin, cmax, POSSESSIVE);
3155                 } else {
3156                     curly = new Curly(prev, cmin, cmax, GREEDY);
3157                 }
3158                 return curly;
3159             } else {
3160                 throw error("Illegal repetition");
3161             }
3162         default:
3163             return prev;
3164         }
3165     }
3166 
3167     /**
3168      *  Utility method for parsing control escape sequences.
3169      */
3170     private int c() {
3171         if (cursor < patternLength) {
3172             return read() ^ 64;
3173         }
3174         throw error("Illegal control escape sequence");
3175     }
3176 
3177     /**
3178      *  Utility method for parsing octal escape sequences.
3179      */
3180     private int o() {
3181         int n = read();
3182         if (((n-'0')|('7'-n)) >= 0) {
3183             int m = read();
3184             if (((m-'0')|('7'-m)) >= 0) {
3185                 int o = read();
3186                 if ((((o-'0')|('7'-o)) >= 0) && (((n-'0')|('3'-n)) >= 0)) {
3187                     return (n - '0') * 64 + (m - '0') * 8 + (o - '0');
3188                 }
3189                 unread();
3190                 return (n - '0') * 8 + (m - '0');
3191             }
3192             unread();
3193             return (n - '0');
3194         }
3195         throw error("Illegal octal escape sequence");
3196     }
3197 
3198     /**
3199      *  Utility method for parsing hexadecimal escape sequences.
3200      */
3201     private int x() {
3202         int n = read();
3203         if (ASCII.isHexDigit(n)) {
3204             int m = read();
3205             if (ASCII.isHexDigit(m)) {
3206                 return ASCII.toDigit(n) * 16 + ASCII.toDigit(m);
3207             }
3208         } else if (n == '{' && ASCII.isHexDigit(peek())) {
3209             int ch = 0;
3210             while (ASCII.isHexDigit(n = read())) {
3211                 ch = (ch << 4) + ASCII.toDigit(n);
3212                 if (ch > Character.MAX_CODE_POINT)
3213                     throw error("Hexadecimal codepoint is too big");
3214             }
3215             if (n != '}')
3216                 throw error("Unclosed hexadecimal escape sequence");
3217             return ch;
3218         }
3219         throw error("Illegal hexadecimal escape sequence");
3220     }
3221 
3222     /**
3223      *  Utility method for parsing unicode escape sequences.
3224      */
3225     private int cursor() {
3226         return cursor;
3227     }
3228 
3229     private void setcursor(int pos) {
3230         cursor = pos;
3231     }
3232 
3233     private int uxxxx() {
3234         int n = 0;
3235         for (int i = 0; i < 4; i++) {
3236             int ch = read();
3237             if (!ASCII.isHexDigit(ch)) {
3238                 throw error("Illegal Unicode escape sequence");
3239             }
3240             n = n * 16 + ASCII.toDigit(ch);
3241         }
3242         return n;
3243     }
3244 
3245     private int u() {
3246         int n = uxxxx();
3247         if (Character.isHighSurrogate((char)n)) {
3248             int cur = cursor();
3249             if (read() == '\\' && read() == 'u') {
3250                 int n2 = uxxxx();
3251                 if (Character.isLowSurrogate((char)n2))
3252                     return Character.toCodePoint((char)n, (char)n2);
3253             }
3254             setcursor(cur);
3255         }
3256         return n;
3257     }
3258 
3259     //
3260     // Utility methods for code point support
3261     //
3262 
3263     private static final int countChars(CharSequence seq, int index,
3264                                         int lengthInCodePoints) {
3265         // optimization
3266         if (lengthInCodePoints == 1 && !Character.isHighSurrogate(seq.charAt(index))) {
3267             assert (index >= 0 && index < seq.length());
3268             return 1;
3269         }
3270         int length = seq.length();
3271         int x = index;
3272         if (lengthInCodePoints >= 0) {
3273             assert (index >= 0 && index < length);
3274             for (int i = 0; x < length && i < lengthInCodePoints; i++) {
3275                 if (Character.isHighSurrogate(seq.charAt(x++))) {
3276                     if (x < length && Character.isLowSurrogate(seq.charAt(x))) {
3277                         x++;
3278                     }
3279                 }
3280             }
3281             return x - index;
3282         }
3283 
3284         assert (index >= 0 && index <= length);
3285         if (index == 0) {
3286             return 0;
3287         }
3288         int len = -lengthInCodePoints;
3289         for (int i = 0; x > 0 && i < len; i++) {
3290             if (Character.isLowSurrogate(seq.charAt(--x))) {
3291                 if (x > 0 && Character.isHighSurrogate(seq.charAt(x-1))) {
3292                     x--;
3293                 }
3294             }
3295         }
3296         return index - x;
3297     }
3298 
3299     private static final int countCodePoints(CharSequence seq) {
3300         int length = seq.length();
3301         int n = 0;
3302         for (int i = 0; i < length; ) {
3303             n++;
3304             if (Character.isHighSurrogate(seq.charAt(i++))) {
3305                 if (i < length && Character.isLowSurrogate(seq.charAt(i))) {
3306                     i++;
3307                 }
3308             }
3309         }
3310         return n;
3311     }
3312 
3313     /**
3314      *  Creates a bit vector for matching Latin-1 values. A normal BitClass
3315      *  never matches values above Latin-1, and a complemented BitClass always
3316      *  matches values above Latin-1.
3317      */
3318     private static final class BitClass extends BmpCharProperty {
3319         final boolean[] bits;
3320         BitClass() { bits = new boolean[256]; }
3321         private BitClass(boolean[] bits) { this.bits = bits; }
3322         BitClass add(int c, int flags) {
3323             assert c >= 0 && c <= 255;
3324             if ((flags & CASE_INSENSITIVE) != 0) {
3325                 if (ASCII.isAscii(c)) {
3326                     bits[ASCII.toUpper(c)] = true;
3327                     bits[ASCII.toLower(c)] = true;
3328                 } else if ((flags & UNICODE_CASE) != 0) {
3329                     bits[Character.toLowerCase(c)] = true;
3330                     bits[Character.toUpperCase(c)] = true;
3331                 }
3332             }
3333             bits[c] = true;
3334             return this;
3335         }
3336         boolean isSatisfiedBy(int ch) {
3337             return ch < 256 && bits[ch];
3338         }
3339     }
3340 
3341     /**
3342      *  Returns a suitably optimized, single character matcher.
3343      */
3344     private CharProperty newSingle(final int ch) {
3345         if (has(CASE_INSENSITIVE)) {
3346             int lower, upper;
3347             if (has(UNICODE_CASE)) {
3348                 upper = Character.toUpperCase(ch);
3349                 lower = Character.toLowerCase(upper);
3350                 if (upper != lower)
3351                     return new SingleU(lower);
3352             } else if (ASCII.isAscii(ch)) {
3353                 lower = ASCII.toLower(ch);
3354                 upper = ASCII.toUpper(ch);
3355                 if (lower != upper)
3356                     return new SingleI(lower, upper);
3357             }
3358         }
3359         if (isSupplementary(ch))
3360             return new SingleS(ch);    // Match a given Unicode character
3361         return new Single(ch);         // Match a given BMP character
3362     }
3363 
3364     /**
3365      *  Utility method for creating a string slice matcher.
3366      */
3367     private Node newSlice(int[] buf, int count, boolean hasSupplementary) {
3368         int[] tmp = new int[count];
3369         if (has(CASE_INSENSITIVE)) {
3370             if (has(UNICODE_CASE)) {
3371                 for (int i = 0; i < count; i++) {
3372                     tmp[i] = Character.toLowerCase(
3373                                  Character.toUpperCase(buf[i]));
3374                 }
3375                 return hasSupplementary? new SliceUS(tmp) : new SliceU(tmp);
3376             }
3377             for (int i = 0; i < count; i++) {
3378                 tmp[i] = ASCII.toLower(buf[i]);
3379             }
3380             return hasSupplementary? new SliceIS(tmp) : new SliceI(tmp);
3381         }
3382         for (int i = 0; i < count; i++) {
3383             tmp[i] = buf[i];
3384         }
3385         return hasSupplementary ? new SliceS(tmp) : new Slice(tmp);
3386     }
3387 
3388     /**
3389      * The following classes are the building components of the object
3390      * tree that represents a compiled regular expression. The object tree
3391      * is made of individual elements that handle constructs in the Pattern.
3392      * Each type of object knows how to match its equivalent construct with
3393      * the match() method.
3394      */
3395 
3396     /**
3397      * Base class for all node classes. Subclasses should override the match()
3398      * method as appropriate. This class is an accepting node, so its match()
3399      * always returns true.
3400      */
3401     static class Node extends Object {
3402         Node next;
3403         Node() {
3404             next = Pattern.accept;
3405         }
3406         /**
3407          * This method implements the classic accept node.
3408          */
3409         boolean match(Matcher matcher, int i, CharSequence seq) {
3410             matcher.last = i;
3411             matcher.groups[0] = matcher.first;
3412             matcher.groups[1] = matcher.last;
3413             return true;
3414         }
3415         /**
3416          * This method is good for all zero length assertions.
3417          */
3418         boolean study(TreeInfo info) {
3419             if (next != null) {
3420                 return next.study(info);
3421             } else {
3422                 return info.deterministic;
3423             }
3424         }
3425     }
3426 
3427     static class LastNode extends Node {
3428         /**
3429          * This method implements the classic accept node with
3430          * the addition of a check to see if the match occurred
3431          * using all of the input.
3432          */
3433         boolean match(Matcher matcher, int i, CharSequence seq) {
3434             if (matcher.acceptMode == Matcher.ENDANCHOR && i != matcher.to)
3435                 return false;
3436             matcher.last = i;
3437             matcher.groups[0] = matcher.first;
3438             matcher.groups[1] = matcher.last;
3439             return true;
3440         }
3441     }
3442 
3443     /**
3444      * Used for REs that can start anywhere within the input string.
3445      * This basically tries to match repeatedly at each spot in the
3446      * input string, moving forward after each try. An anchored search
3447      * or a BnM will bypass this node completely.
3448      */
3449     static class Start extends Node {
3450         int minLength;
3451         Start(Node node) {
3452             this.next = node;
3453             TreeInfo info = new TreeInfo();
3454             next.study(info);
3455             minLength = info.minLength;
3456         }
3457         boolean match(Matcher matcher, int i, CharSequence seq) {
3458             if (i > matcher.to - minLength) {
3459                 matcher.hitEnd = true;
3460                 return false;
3461             }
3462             int guard = matcher.to - minLength;
3463             for (; i <= guard; i++) {
3464                 if (next.match(matcher, i, seq)) {
3465                     matcher.first = i;
3466                     matcher.groups[0] = matcher.first;
3467                     matcher.groups[1] = matcher.last;
3468                     return true;
3469                 }
3470             }
3471             matcher.hitEnd = true;
3472             return false;
3473         }
3474         boolean study(TreeInfo info) {
3475             next.study(info);
3476             info.maxValid = false;
3477             info.deterministic = false;
3478             return false;
3479         }
3480     }
3481 
3482     /*
3483      * StartS supports supplementary characters, including unpaired surrogates.
3484      */
3485     static final class StartS extends Start {
3486         StartS(Node node) {
3487             super(node);
3488         }
3489         boolean match(Matcher matcher, int i, CharSequence seq) {
3490             if (i > matcher.to - minLength) {
3491                 matcher.hitEnd = true;
3492                 return false;
3493             }
3494             int guard = matcher.to - minLength;
3495             while (i <= guard) {
3496                 //if ((ret = next.match(matcher, i, seq)) || i == guard)
3497                 if (next.match(matcher, i, seq)) {
3498                     matcher.first = i;
3499                     matcher.groups[0] = matcher.first;
3500                     matcher.groups[1] = matcher.last;
3501                     return true;
3502                 }
3503                 if (i == guard)
3504                     break;
3505                 // Optimization to move to the next character. This is
3506                 // faster than countChars(seq, i, 1).
3507                 if (Character.isHighSurrogate(seq.charAt(i++))) {
3508                     if (i < seq.length() &&
3509                         Character.isLowSurrogate(seq.charAt(i))) {
3510                         i++;
3511                     }
3512                 }
3513             }
3514             matcher.hitEnd = true;
3515             return false;
3516         }
3517     }
3518 
3519     /**
3520      * Node to anchor at the beginning of input. This object implements the
3521      * match for a \A sequence, and the caret anchor will use this if not in
3522      * multiline mode.
3523      */
3524     static final class Begin extends Node {
3525         boolean match(Matcher matcher, int i, CharSequence seq) {
3526             int fromIndex = (matcher.anchoringBounds) ?
3527                 matcher.from : 0;
3528             if (i == fromIndex && next.match(matcher, i, seq)) {
3529                 matcher.first = i;
3530                 matcher.groups[0] = i;
3531                 matcher.groups[1] = matcher.last;
3532                 return true;
3533             } else {
3534                 return false;
3535             }
3536         }
3537     }
3538 
3539     /**
3540      * Node to anchor at the end of input. This is the absolute end, so this
3541      * should not match at the last newline before the end as $ will.
3542      */
3543     static final class End extends Node {
3544         boolean match(Matcher matcher, int i, CharSequence seq) {
3545             int endIndex = (matcher.anchoringBounds) ?
3546                 matcher.to : matcher.getTextLength();
3547             if (i == endIndex) {
3548                 matcher.hitEnd = true;
3549                 return next.match(matcher, i, seq);
3550             }
3551             return false;
3552         }
3553     }
3554 
3555     /**
3556      * Node to anchor at the beginning of a line. This is essentially the
3557      * object to match for the multiline ^.
3558      */
3559     static final class Caret extends Node {
3560         boolean match(Matcher matcher, int i, CharSequence seq) {
3561             int startIndex = matcher.from;
3562             int endIndex = matcher.to;
3563             if (!matcher.anchoringBounds) {
3564                 startIndex = 0;
3565                 endIndex = matcher.getTextLength();
3566             }
3567             // Perl does not match ^ at end of input even after newline
3568             if (i == endIndex) {
3569                 matcher.hitEnd = true;
3570                 return false;
3571             }
3572             if (i > startIndex) {
3573                 char ch = seq.charAt(i-1);
3574                 if (ch != '\n' && ch != '\r'
3575                     && (ch|1) != '\u2029'
3576                     && ch != '\u0085' ) {
3577                     return false;
3578                 }
3579                 // Should treat /r/n as one newline
3580                 if (ch == '\r' && seq.charAt(i) == '\n')
3581                     return false;
3582             }
3583             return next.match(matcher, i, seq);
3584         }
3585     }
3586 
3587     /**
3588      * Node to anchor at the beginning of a line when in unixdot mode.
3589      */
3590     static final class UnixCaret extends Node {
3591         boolean match(Matcher matcher, int i, CharSequence seq) {
3592             int startIndex = matcher.from;
3593             int endIndex = matcher.to;
3594             if (!matcher.anchoringBounds) {
3595                 startIndex = 0;
3596                 endIndex = matcher.getTextLength();
3597             }
3598             // Perl does not match ^ at end of input even after newline
3599             if (i == endIndex) {
3600                 matcher.hitEnd = true;
3601                 return false;
3602             }
3603             if (i > startIndex) {
3604                 char ch = seq.charAt(i-1);
3605                 if (ch != '\n') {
3606                     return false;
3607                 }
3608             }
3609             return next.match(matcher, i, seq);
3610         }
3611     }
3612 
3613     /**
3614      * Node to match the location where the last match ended.
3615      * This is used for the \G construct.
3616      */
3617     static final class LastMatch extends Node {
3618         boolean match(Matcher matcher, int i, CharSequence seq) {
3619             if (i != matcher.oldLast)
3620                 return false;
3621             return next.match(matcher, i, seq);
3622         }
3623     }
3624 
3625     /**
3626      * Node to anchor at the end of a line or the end of input based on the
3627      * multiline mode.
3628      *
3629      * When not in multiline mode, the $ can only match at the very end
3630      * of the input, unless the input ends in a line terminator in which
3631      * it matches right before the last line terminator.
3632      *
3633      * Note that \r\n is considered an atomic line terminator.
3634      *
3635      * Like ^ the $ operator matches at a position, it does not match the
3636      * line terminators themselves.
3637      */
3638     static final class Dollar extends Node {
3639         boolean multiline;
3640         Dollar(boolean mul) {
3641             multiline = mul;
3642         }
3643         boolean match(Matcher matcher, int i, CharSequence seq) {
3644             int endIndex = (matcher.anchoringBounds) ?
3645                 matcher.to : matcher.getTextLength();
3646             if (!multiline) {
3647                 if (i < endIndex - 2)
3648                     return false;
3649                 if (i == endIndex - 2) {
3650                     char ch = seq.charAt(i);
3651                     if (ch != '\r')
3652                         return false;
3653                     ch = seq.charAt(i + 1);
3654                     if (ch != '\n')
3655                         return false;
3656                 }
3657             }
3658             // Matches before any line terminator; also matches at the
3659             // end of input
3660             // Before line terminator:
3661             // If multiline, we match here no matter what
3662             // If not multiline, fall through so that the end
3663             // is marked as hit; this must be a /r/n or a /n
3664             // at the very end so the end was hit; more input
3665             // could make this not match here
3666             if (i < endIndex) {
3667                 char ch = seq.charAt(i);
3668                  if (ch == '\n') {
3669                      // No match between \r\n
3670                      if (i > 0 && seq.charAt(i-1) == '\r')
3671                          return false;
3672                      if (multiline)
3673                          return next.match(matcher, i, seq);
3674                  } else if (ch == '\r' || ch == '\u0085' ||
3675                             (ch|1) == '\u2029') {
3676                      if (multiline)
3677                          return next.match(matcher, i, seq);
3678                  } else { // No line terminator, no match
3679                      return false;
3680                  }
3681             }
3682             // Matched at current end so hit end
3683             matcher.hitEnd = true;
3684             // If a $ matches because of end of input, then more input
3685             // could cause it to fail!
3686             matcher.requireEnd = true;
3687             return next.match(matcher, i, seq);
3688         }
3689         boolean study(TreeInfo info) {
3690             next.study(info);
3691             return info.deterministic;
3692         }
3693     }
3694 
3695     /**
3696      * Node to anchor at the end of a line or the end of input based on the
3697      * multiline mode when in unix lines mode.
3698      */
3699     static final class UnixDollar extends Node {
3700         boolean multiline;
3701         UnixDollar(boolean mul) {
3702             multiline = mul;
3703         }
3704         boolean match(Matcher matcher, int i, CharSequence seq) {
3705             int endIndex = (matcher.anchoringBounds) ?
3706                 matcher.to : matcher.getTextLength();
3707             if (i < endIndex) {
3708                 char ch = seq.charAt(i);
3709                 if (ch == '\n') {
3710                     // If not multiline, then only possible to
3711                     // match at very end or one before end
3712                     if (multiline == false && i != endIndex - 1)
3713                         return false;
3714                     // If multiline return next.match without setting
3715                     // matcher.hitEnd
3716                     if (multiline)
3717                         return next.match(matcher, i, seq);
3718                 } else {
3719                     return false;
3720                 }
3721             }
3722             // Matching because at the end or 1 before the end;
3723             // more input could change this so set hitEnd
3724             matcher.hitEnd = true;
3725             // If a $ matches because of end of input, then more input
3726             // could cause it to fail!
3727             matcher.requireEnd = true;
3728             return next.match(matcher, i, seq);
3729         }
3730         boolean study(TreeInfo info) {
3731             next.study(info);
3732             return info.deterministic;
3733         }
3734     }
3735 
3736     /**
3737      * Node class that matches a Unicode line ending '\R'
3738      */
3739     static final class LineEnding extends Node {
3740         boolean match(Matcher matcher, int i, CharSequence seq) {
3741             // (u+000Du+000A|[u+000Au+000Bu+000Cu+000Du+0085u+2028u+2029])
3742             if (i < matcher.to) {
3743                 int ch = seq.charAt(i);
3744                 if (ch == 0x0A || ch == 0x0B || ch == 0x0C ||
3745                     ch == 0x85 || ch == 0x2028 || ch == 0x2029)
3746                     return next.match(matcher, i + 1, seq);
3747                 if (ch == 0x0D) {
3748                     i++;
3749                     if (i < matcher.to && seq.charAt(i) == 0x0A)
3750                         i++;
3751                     return next.match(matcher, i, seq);
3752                 }
3753             } else {
3754                 matcher.hitEnd = true;
3755             }
3756             return false;
3757         }
3758         boolean study(TreeInfo info) {
3759             info.minLength++;
3760             info.maxLength += 2;
3761             return next.study(info);
3762         }
3763     }
3764 
3765     /**
3766      * Abstract node class to match one character satisfying some
3767      * boolean property.
3768      */
3769     private static abstract class CharProperty extends Node {
3770         abstract boolean isSatisfiedBy(int ch);
3771         CharProperty complement() {
3772             return new CharProperty() {
3773                     boolean isSatisfiedBy(int ch) {
3774                         return ! CharProperty.this.isSatisfiedBy(ch);}};
3775         }
3776         boolean match(Matcher matcher, int i, CharSequence seq) {
3777             if (i < matcher.to) {
3778                 int ch = Character.codePointAt(seq, i);
3779                 return isSatisfiedBy(ch)
3780                     && next.match(matcher, i+Character.charCount(ch), seq);
3781             } else {
3782                 matcher.hitEnd = true;
3783                 return false;
3784             }
3785         }
3786         boolean study(TreeInfo info) {
3787             info.minLength++;
3788             info.maxLength++;
3789             return next.study(info);
3790         }
3791     }
3792 
3793     /**
3794      * Optimized version of CharProperty that works only for
3795      * properties never satisfied by Supplementary characters.
3796      */
3797     private static abstract class BmpCharProperty extends CharProperty {
3798         boolean match(Matcher matcher, int i, CharSequence seq) {
3799             if (i < matcher.to) {
3800                 return isSatisfiedBy(seq.charAt(i))
3801                     && next.match(matcher, i+1, seq);
3802             } else {
3803                 matcher.hitEnd = true;
3804                 return false;
3805             }
3806         }
3807     }
3808 
3809     /**
3810      * Node class that matches a Supplementary Unicode character
3811      */
3812     static final class SingleS extends CharProperty {
3813         final int c;
3814         SingleS(int c) { this.c = c; }
3815         boolean isSatisfiedBy(int ch) {
3816             return ch == c;
3817         }
3818     }
3819 
3820     /**
3821      * Optimization -- matches a given BMP character
3822      */
3823     static final class Single extends BmpCharProperty {
3824         final int c;
3825         Single(int c) { this.c = c; }
3826         boolean isSatisfiedBy(int ch) {
3827             return ch == c;
3828         }
3829     }
3830 
3831     /**
3832      * Case insensitive matches a given BMP character
3833      */
3834     static final class SingleI extends BmpCharProperty {
3835         final int lower;
3836         final int upper;
3837         SingleI(int lower, int upper) {
3838             this.lower = lower;
3839             this.upper = upper;
3840         }
3841         boolean isSatisfiedBy(int ch) {
3842             return ch == lower || ch == upper;
3843         }
3844     }
3845 
3846     /**
3847      * Unicode case insensitive matches a given Unicode character
3848      */
3849     static final class SingleU extends CharProperty {
3850         final int lower;
3851         SingleU(int lower) {
3852             this.lower = lower;
3853         }
3854         boolean isSatisfiedBy(int ch) {
3855             return lower == ch ||
3856                 lower == Character.toLowerCase(Character.toUpperCase(ch));
3857         }
3858     }
3859 
3860     /**
3861      * Node class that matches a Unicode block.
3862      */
3863     static final class Block extends CharProperty {
3864         final Character.UnicodeBlock block;
3865         Block(Character.UnicodeBlock block) {
3866             this.block = block;
3867         }
3868         boolean isSatisfiedBy(int ch) {
3869             return block == Character.UnicodeBlock.of(ch);
3870         }
3871     }
3872 
3873     /**
3874      * Node class that matches a Unicode script
3875      */
3876     static final class Script extends CharProperty {
3877         final Character.UnicodeScript script;
3878         Script(Character.UnicodeScript script) {
3879             this.script = script;
3880         }
3881         boolean isSatisfiedBy(int ch) {
3882             return script == Character.UnicodeScript.of(ch);
3883         }
3884     }
3885 
3886     /**
3887      * Node class that matches a Unicode category.
3888      */
3889     static final class Category extends CharProperty {
3890         final int typeMask;
3891         Category(int typeMask) { this.typeMask = typeMask; }
3892         boolean isSatisfiedBy(int ch) {
3893             return (typeMask & (1 << Character.getType(ch))) != 0;
3894         }
3895     }
3896 
3897     /**
3898      * Node class that matches a Unicode "type"
3899      */
3900     static final class Utype extends CharProperty {
3901         final UnicodeProp uprop;
3902         Utype(UnicodeProp uprop) { this.uprop = uprop; }
3903         boolean isSatisfiedBy(int ch) {
3904             return uprop.is(ch);
3905         }
3906     }
3907 
3908     /**
3909      * Node class that matches a POSIX type.
3910      */
3911     static final class Ctype extends BmpCharProperty {
3912         final int ctype;
3913         Ctype(int ctype) { this.ctype = ctype; }
3914         boolean isSatisfiedBy(int ch) {
3915             return ch < 128 && ASCII.isType(ch, ctype);
3916         }
3917     }
3918 
3919     /**
3920      * Node class that matches a Perl vertical whitespace
3921      */
3922     static final class VertWS extends BmpCharProperty {
3923         boolean isSatisfiedBy(int cp) {
3924             return (cp >= 0x0A && cp <= 0x0D) ||
3925                    cp == 0x85 || cp == 0x2028 || cp == 0x2029;
3926         }
3927     }
3928 
3929     /**
3930      * Node class that matches a Perl horizontal whitespace
3931      */
3932     static final class HorizWS extends BmpCharProperty {
3933         boolean isSatisfiedBy(int cp) {
3934             return cp == 0x09 || cp == 0x20 || cp == 0xa0 ||
3935                    cp == 0x1680 || cp == 0x180e ||
3936                    cp >= 0x2000 && cp <= 0x200a ||
3937                    cp == 0x202f || cp == 0x205f || cp == 0x3000;
3938         }
3939     }
3940 
3941     /**
3942      * Base class for all Slice nodes
3943      */
3944     static class SliceNode extends Node {
3945         int[] buffer;
3946         SliceNode(int[] buf) {
3947             buffer = buf;
3948         }
3949         boolean study(TreeInfo info) {
3950             info.minLength += buffer.length;
3951             info.maxLength += buffer.length;
3952             return next.study(info);
3953         }
3954     }
3955 
3956     /**
3957      * Node class for a case sensitive/BMP-only sequence of literal
3958      * characters.
3959      */
3960     static final class Slice extends SliceNode {
3961         Slice(int[] buf) {
3962             super(buf);
3963         }
3964         boolean match(Matcher matcher, int i, CharSequence seq) {
3965             int[] buf = buffer;
3966             int len = buf.length;
3967             for (int j=0; j<len; j++) {
3968                 if ((i+j) >= matcher.to) {
3969                     matcher.hitEnd = true;
3970                     return false;
3971                 }
3972                 if (buf[j] != seq.charAt(i+j))
3973                     return false;
3974             }
3975             return next.match(matcher, i+len, seq);
3976         }
3977     }
3978 
3979     /**
3980      * Node class for a case_insensitive/BMP-only sequence of literal
3981      * characters.
3982      */
3983     static class SliceI extends SliceNode {
3984         SliceI(int[] buf) {
3985             super(buf);
3986         }
3987         boolean match(Matcher matcher, int i, CharSequence seq) {
3988             int[] buf = buffer;
3989             int len = buf.length;
3990             for (int j=0; j<len; j++) {
3991                 if ((i+j) >= matcher.to) {
3992                     matcher.hitEnd = true;
3993                     return false;
3994                 }
3995                 int c = seq.charAt(i+j);
3996                 if (buf[j] != c &&
3997                     buf[j] != ASCII.toLower(c))
3998                     return false;
3999             }
4000             return next.match(matcher, i+len, seq);
4001         }
4002     }
4003 
4004     /**
4005      * Node class for a unicode_case_insensitive/BMP-only sequence of
4006      * literal characters. Uses unicode case folding.
4007      */
4008     static final class SliceU extends SliceNode {
4009         SliceU(int[] buf) {
4010             super(buf);
4011         }
4012         boolean match(Matcher matcher, int i, CharSequence seq) {
4013             int[] buf = buffer;
4014             int len = buf.length;
4015             for (int j=0; j<len; j++) {
4016                 if ((i+j) >= matcher.to) {
4017                     matcher.hitEnd = true;
4018                     return false;
4019                 }
4020                 int c = seq.charAt(i+j);
4021                 if (buf[j] != c &&
4022                     buf[j] != Character.toLowerCase(Character.toUpperCase(c)))
4023                     return false;
4024             }
4025             return next.match(matcher, i+len, seq);
4026         }
4027     }
4028 
4029     /**
4030      * Node class for a case sensitive sequence of literal characters
4031      * including supplementary characters.
4032      */
4033     static final class SliceS extends SliceNode {
4034         SliceS(int[] buf) {
4035             super(buf);
4036         }
4037         boolean match(Matcher matcher, int i, CharSequence seq) {
4038             int[] buf = buffer;
4039             int x = i;
4040             for (int j = 0; j < buf.length; j++) {
4041                 if (x >= matcher.to) {
4042                     matcher.hitEnd = true;
4043                     return false;
4044                 }
4045                 int c = Character.codePointAt(seq, x);
4046                 if (buf[j] != c)
4047                     return false;
4048                 x += Character.charCount(c);
4049                 if (x > matcher.to) {
4050                     matcher.hitEnd = true;
4051                     return false;
4052                 }
4053             }
4054             return next.match(matcher, x, seq);
4055         }
4056     }
4057 
4058     /**
4059      * Node class for a case insensitive sequence of literal characters
4060      * including supplementary characters.
4061      */
4062     static class SliceIS extends SliceNode {
4063         SliceIS(int[] buf) {
4064             super(buf);
4065         }
4066         int toLower(int c) {
4067             return ASCII.toLower(c);
4068         }
4069         boolean match(Matcher matcher, int i, CharSequence seq) {
4070             int[] buf = buffer;
4071             int x = i;
4072             for (int j = 0; j < buf.length; j++) {
4073                 if (x >= matcher.to) {
4074                     matcher.hitEnd = true;
4075                     return false;
4076                 }
4077                 int c = Character.codePointAt(seq, x);
4078                 if (buf[j] != c && buf[j] != toLower(c))
4079                     return false;
4080                 x += Character.charCount(c);
4081                 if (x > matcher.to) {
4082                     matcher.hitEnd = true;
4083                     return false;
4084                 }
4085             }
4086             return next.match(matcher, x, seq);
4087         }
4088     }
4089 
4090     /**
4091      * Node class for a case insensitive sequence of literal characters.
4092      * Uses unicode case folding.
4093      */
4094     static final class SliceUS extends SliceIS {
4095         SliceUS(int[] buf) {
4096             super(buf);
4097         }
4098         int toLower(int c) {
4099             return Character.toLowerCase(Character.toUpperCase(c));
4100         }
4101     }
4102 
4103     private static boolean inRange(int lower, int ch, int upper) {
4104         return lower <= ch && ch <= upper;
4105     }
4106 
4107     /**
4108      * Returns node for matching characters within an explicit value range.
4109      */
4110     private static CharProperty rangeFor(final int lower,
4111                                          final int upper) {
4112         return new CharProperty() {
4113                 boolean isSatisfiedBy(int ch) {
4114                     return inRange(lower, ch, upper);}};
4115     }
4116 
4117     /**
4118      * Returns node for matching characters within an explicit value
4119      * range in a case insensitive manner.
4120      */
4121     private CharProperty caseInsensitiveRangeFor(final int lower,
4122                                                  final int upper) {
4123         if (has(UNICODE_CASE))
4124             return new CharProperty() {
4125                 boolean isSatisfiedBy(int ch) {
4126                     if (inRange(lower, ch, upper))
4127                         return true;
4128                     int up = Character.toUpperCase(ch);
4129                     return inRange(lower, up, upper) ||
4130                            inRange(lower, Character.toLowerCase(up), upper);}};
4131         return new CharProperty() {
4132             boolean isSatisfiedBy(int ch) {
4133                 return inRange(lower, ch, upper) ||
4134                     ASCII.isAscii(ch) &&
4135                         (inRange(lower, ASCII.toUpper(ch), upper) ||
4136                          inRange(lower, ASCII.toLower(ch), upper));
4137             }};
4138     }
4139 
4140     /**
4141      * Implements the Unicode category ALL and the dot metacharacter when
4142      * in dotall mode.
4143      */
4144     static final class All extends CharProperty {
4145         boolean isSatisfiedBy(int ch) {
4146             return true;
4147         }
4148     }
4149 
4150     /**
4151      * Node class for the dot metacharacter when dotall is not enabled.
4152      */
4153     static final class Dot extends CharProperty {
4154         boolean isSatisfiedBy(int ch) {
4155             return (ch != '\n' && ch != '\r'
4156                     && (ch|1) != '\u2029'
4157                     && ch != '\u0085');
4158         }
4159     }
4160 
4161     /**
4162      * Node class for the dot metacharacter when dotall is not enabled
4163      * but UNIX_LINES is enabled.
4164      */
4165     static final class UnixDot extends CharProperty {
4166         boolean isSatisfiedBy(int ch) {
4167             return ch != '\n';
4168         }
4169     }
4170 
4171     /**
4172      * The 0 or 1 quantifier. This one class implements all three types.
4173      */
4174     static final class Ques extends Node {
4175         Node atom;
4176         int type;
4177         Ques(Node node, int type) {
4178             this.atom = node;
4179             this.type = type;
4180         }
4181         boolean match(Matcher matcher, int i, CharSequence seq) {
4182             switch (type) {
4183             case GREEDY:
4184                 return (atom.match(matcher, i, seq) && next.match(matcher, matcher.last, seq))
4185                     || next.match(matcher, i, seq);
4186             case LAZY:
4187                 return next.match(matcher, i, seq)
4188                     || (atom.match(matcher, i, seq) && next.match(matcher, matcher.last, seq));
4189             case POSSESSIVE:
4190                 if (atom.match(matcher, i, seq)) i = matcher.last;
4191                 return next.match(matcher, i, seq);
4192             default:
4193                 return atom.match(matcher, i, seq) && next.match(matcher, matcher.last, seq);
4194             }
4195         }
4196         boolean study(TreeInfo info) {
4197             if (type != INDEPENDENT) {
4198                 int minL = info.minLength;
4199                 atom.study(info);
4200                 info.minLength = minL;
4201                 info.deterministic = false;
4202                 return next.study(info);
4203             } else {
4204                 atom.study(info);
4205                 return next.study(info);
4206             }
4207         }
4208     }
4209 
4210     /**
4211      * Handles the curly-brace style repetition with a specified minimum and
4212      * maximum occurrences. The * quantifier is handled as a special case.
4213      * This class handles the three types.
4214      */
4215     static final class Curly extends Node {
4216         Node atom;
4217         int type;
4218         int cmin;
4219         int cmax;
4220 
4221         Curly(Node node, int cmin, int cmax, int type) {
4222             this.atom = node;
4223             this.type = type;
4224             this.cmin = cmin;
4225             this.cmax = cmax;
4226         }
4227         boolean match(Matcher matcher, int i, CharSequence seq) {
4228             int j;
4229             for (j = 0; j < cmin; j++) {
4230                 if (atom.match(matcher, i, seq)) {
4231                     i = matcher.last;
4232                     continue;
4233                 }
4234                 return false;
4235             }
4236             if (type == GREEDY)
4237                 return match0(matcher, i, j, seq);
4238             else if (type == LAZY)
4239                 return match1(matcher, i, j, seq);
4240             else
4241                 return match2(matcher, i, j, seq);
4242         }
4243         // Greedy match.
4244         // i is the index to start matching at
4245         // j is the number of atoms that have matched
4246         boolean match0(Matcher matcher, int i, int j, CharSequence seq) {
4247             if (j >= cmax) {
4248                 // We have matched the maximum... continue with the rest of
4249                 // the regular expression
4250                 return next.match(matcher, i, seq);
4251             }
4252             int backLimit = j;
4253             while (atom.match(matcher, i, seq)) {
4254                 // k is the length of this match
4255                 int k = matcher.last - i;
4256                 if (k == 0) // Zero length match
4257                     break;
4258                 // Move up index and number matched
4259                 i = matcher.last;
4260                 j++;
4261                 // We are greedy so match as many as we can
4262                 while (j < cmax) {
4263                     if (!atom.match(matcher, i, seq))
4264                         break;
4265                     if (i + k != matcher.last) {
4266                         if (match0(matcher, matcher.last, j+1, seq))
4267                             return true;
4268                         break;
4269                     }
4270                     i += k;
4271                     j++;
4272                 }
4273                 // Handle backing off if match fails
4274                 while (j >= backLimit) {
4275                    if (next.match(matcher, i, seq))
4276                         return true;
4277                     i -= k;
4278                     j--;
4279                 }
4280                 return false;
4281             }
4282             return next.match(matcher, i, seq);
4283         }
4284         // Reluctant match. At this point, the minimum has been satisfied.
4285         // i is the index to start matching at
4286         // j is the number of atoms that have matched
4287         boolean match1(Matcher matcher, int i, int j, CharSequence seq) {
4288             for (;;) {
4289                 // Try finishing match without consuming any more
4290                 if (next.match(matcher, i, seq))
4291                     return true;
4292                 // At the maximum, no match found
4293                 if (j >= cmax)
4294                     return false;
4295                 // Okay, must try one more atom
4296                 if (!atom.match(matcher, i, seq))
4297                     return false;
4298                 // If we haven't moved forward then must break out
4299                 if (i == matcher.last)
4300                     return false;
4301                 // Move up index and number matched
4302                 i = matcher.last;
4303                 j++;
4304             }
4305         }
4306         boolean match2(Matcher matcher, int i, int j, CharSequence seq) {
4307             for (; j < cmax; j++) {
4308                 if (!atom.match(matcher, i, seq))
4309                     break;
4310                 if (i == matcher.last)
4311                     break;
4312                 i = matcher.last;
4313             }
4314             return next.match(matcher, i, seq);
4315         }
4316         boolean study(TreeInfo info) {
4317             // Save original info
4318             int minL = info.minLength;
4319             int maxL = info.maxLength;
4320             boolean maxV = info.maxValid;
4321             boolean detm = info.deterministic;
4322             info.reset();
4323 
4324             atom.study(info);
4325 
4326             int temp = info.minLength * cmin + minL;
4327             if (temp < minL) {
4328                 temp = 0xFFFFFFF; // arbitrary large number
4329             }
4330             info.minLength = temp;
4331 
4332             if (maxV & info.maxValid) {
4333                 temp = info.maxLength * cmax + maxL;
4334                 info.maxLength = temp;
4335                 if (temp < maxL) {
4336                     info.maxValid = false;
4337                 }
4338             } else {
4339                 info.maxValid = false;
4340             }
4341 
4342             if (info.deterministic && cmin == cmax)
4343                 info.deterministic = detm;
4344             else
4345                 info.deterministic = false;
4346             return next.study(info);
4347         }
4348     }
4349 
4350     /**
4351      * Handles the curly-brace style repetition with a specified minimum and
4352      * maximum occurrences in deterministic cases. This is an iterative
4353      * optimization over the Prolog and Loop system which would handle this
4354      * in a recursive way. The * quantifier is handled as a special case.
4355      * If capture is true then this class saves group settings and ensures
4356      * that groups are unset when backing off of a group match.
4357      */
4358     static final class GroupCurly extends Node {
4359         Node atom;
4360         int type;
4361         int cmin;
4362         int cmax;
4363         int localIndex;
4364         int groupIndex;
4365         boolean capture;
4366 
4367         GroupCurly(Node node, int cmin, int cmax, int type, int local,
4368                    int group, boolean capture) {
4369             this.atom = node;
4370             this.type = type;
4371             this.cmin = cmin;
4372             this.cmax = cmax;
4373             this.localIndex = local;
4374             this.groupIndex = group;
4375             this.capture = capture;
4376         }
4377         boolean match(Matcher matcher, int i, CharSequence seq) {
4378             int[] groups = matcher.groups;
4379             int[] locals = matcher.locals;
4380             int save0 = locals[localIndex];
4381             int save1 = 0;
4382             int save2 = 0;
4383 
4384             if (capture) {
4385                 save1 = groups[groupIndex];
4386                 save2 = groups[groupIndex+1];
4387             }
4388 
4389             // Notify GroupTail there is no need to setup group info
4390             // because it will be set here
4391             locals[localIndex] = -1;
4392 
4393             boolean ret = true;
4394             for (int j = 0; j < cmin; j++) {
4395                 if (atom.match(matcher, i, seq)) {
4396                     if (capture) {
4397                         groups[groupIndex] = i;
4398                         groups[groupIndex+1] = matcher.last;
4399                     }
4400                     i = matcher.last;
4401                 } else {
4402                     ret = false;
4403                     break;
4404                 }
4405             }
4406             if (ret) {
4407                 if (type == GREEDY) {
4408                     ret = match0(matcher, i, cmin, seq);
4409                 } else if (type == LAZY) {
4410                     ret = match1(matcher, i, cmin, seq);
4411                 } else {
4412                     ret = match2(matcher, i, cmin, seq);
4413                 }
4414             }
4415             if (!ret) {
4416                 locals[localIndex] = save0;
4417                 if (capture) {
4418                     groups[groupIndex] = save1;
4419                     groups[groupIndex+1] = save2;
4420                 }
4421             }
4422             return ret;
4423         }
4424         // Aggressive group match
4425         boolean match0(Matcher matcher, int i, int j, CharSequence seq) {
4426             // don't back off passing the starting "j"
4427             int min = j;
4428             int[] groups = matcher.groups;
4429             int save0 = 0;
4430             int save1 = 0;
4431             if (capture) {
4432                 save0 = groups[groupIndex];
4433                 save1 = groups[groupIndex+1];
4434             }
4435             for (;;) {
4436                 if (j >= cmax)
4437                     break;
4438                 if (!atom.match(matcher, i, seq))
4439                     break;
4440                 int k = matcher.last - i;
4441                 if (k <= 0) {
4442                     if (capture) {
4443                         groups[groupIndex] = i;
4444                         groups[groupIndex+1] = i + k;
4445                     }
4446                     i = i + k;
4447                     break;
4448                 }
4449                 for (;;) {
4450                     if (capture) {
4451                         groups[groupIndex] = i;
4452                         groups[groupIndex+1] = i + k;
4453                     }
4454                     i = i + k;
4455                     if (++j >= cmax)
4456                         break;
4457                     if (!atom.match(matcher, i, seq))
4458                         break;
4459                     if (i + k != matcher.last) {
4460                         if (match0(matcher, i, j, seq))
4461                             return true;
4462                         break;
4463                     }
4464                 }
4465                 while (j > min) {
4466                     if (next.match(matcher, i, seq)) {
4467                         if (capture) {
4468                             groups[groupIndex+1] = i;
4469                             groups[groupIndex] = i - k;
4470                         }
4471                         return true;
4472                     }
4473                     // backing off
4474                     i = i - k;
4475                     if (capture) {
4476                         groups[groupIndex+1] = i;
4477                         groups[groupIndex] = i - k;
4478                     }
4479                     j--;
4480 
4481                 }
4482                 break;
4483             }
4484             if (capture) {
4485                 groups[groupIndex] = save0;
4486                 groups[groupIndex+1] = save1;
4487             }
4488             return next.match(matcher, i, seq);
4489         }
4490         // Reluctant matching
4491         boolean match1(Matcher matcher, int i, int j, CharSequence seq) {
4492             for (;;) {
4493                 if (next.match(matcher, i, seq))
4494                     return true;
4495                 if (j >= cmax)
4496                     return false;
4497                 if (!atom.match(matcher, i, seq))
4498                     return false;
4499                 if (i == matcher.last)
4500                     return false;
4501                 if (capture) {
4502                     matcher.groups[groupIndex] = i;
4503                     matcher.groups[groupIndex+1] = matcher.last;
4504                 }
4505                 i = matcher.last;
4506                 j++;
4507             }
4508         }
4509         // Possessive matching
4510         boolean match2(Matcher matcher, int i, int j, CharSequence seq) {
4511             for (; j < cmax; j++) {
4512                 if (!atom.match(matcher, i, seq)) {
4513                     break;
4514                 }
4515                 if (capture) {
4516                     matcher.groups[groupIndex] = i;
4517                     matcher.groups[groupIndex+1] = matcher.last;
4518                 }
4519                 if (i == matcher.last) {
4520                     break;
4521                 }
4522                 i = matcher.last;
4523             }
4524             return next.match(matcher, i, seq);
4525         }
4526         boolean study(TreeInfo info) {
4527             // Save original info
4528             int minL = info.minLength;
4529             int maxL = info.maxLength;
4530             boolean maxV = info.maxValid;
4531             boolean detm = info.deterministic;
4532             info.reset();
4533 
4534             atom.study(info);
4535 
4536             int temp = info.minLength * cmin + minL;
4537             if (temp < minL) {
4538                 temp = 0xFFFFFFF; // Arbitrary large number
4539             }
4540             info.minLength = temp;
4541 
4542             if (maxV & info.maxValid) {
4543                 temp = info.maxLength * cmax + maxL;
4544                 info.maxLength = temp;
4545                 if (temp < maxL) {
4546                     info.maxValid = false;
4547                 }
4548             } else {
4549                 info.maxValid = false;
4550             }
4551 
4552             if (info.deterministic && cmin == cmax) {
4553                 info.deterministic = detm;
4554             } else {
4555                 info.deterministic = false;
4556             }
4557             return next.study(info);
4558         }
4559     }
4560 
4561     /**
4562      * A Guard node at the end of each atom node in a Branch. It
4563      * serves the purpose of chaining the "match" operation to
4564      * "next" but not the "study", so we can collect the TreeInfo
4565      * of each atom node without including the TreeInfo of the
4566      * "next".
4567      */
4568     static final class BranchConn extends Node {
4569         BranchConn() {};
4570         boolean match(Matcher matcher, int i, CharSequence seq) {
4571             return next.match(matcher, i, seq);
4572         }
4573         boolean study(TreeInfo info) {
4574             return info.deterministic;
4575         }
4576     }
4577 
4578     /**
4579      * Handles the branching of alternations. Note this is also used for
4580      * the ? quantifier to branch between the case where it matches once
4581      * and where it does not occur.
4582      */
4583     static final class Branch extends Node {
4584         Node[] atoms = new Node[2];
4585         int size = 2;
4586         Node conn;
4587         Branch(Node first, Node second, Node branchConn) {
4588             conn = branchConn;
4589             atoms[0] = first;
4590             atoms[1] = second;
4591         }
4592 
4593         void add(Node node) {
4594             if (size >= atoms.length) {
4595                 Node[] tmp = new Node[atoms.length*2];
4596                 System.arraycopy(atoms, 0, tmp, 0, atoms.length);
4597                 atoms = tmp;
4598             }
4599             atoms[size++] = node;
4600         }
4601 
4602         boolean match(Matcher matcher, int i, CharSequence seq) {
4603             for (int n = 0; n < size; n++) {
4604                 if (atoms[n] == null) {
4605                     if (conn.next.match(matcher, i, seq))
4606                         return true;
4607                 } else if (atoms[n].match(matcher, i, seq)) {
4608                     return true;
4609                 }
4610             }
4611             return false;
4612         }
4613 
4614         boolean study(TreeInfo info) {
4615             int minL = info.minLength;
4616             int maxL = info.maxLength;
4617             boolean maxV = info.maxValid;
4618 
4619             int minL2 = Integer.MAX_VALUE; //arbitrary large enough num
4620             int maxL2 = -1;
4621             for (int n = 0; n < size; n++) {
4622                 info.reset();
4623                 if (atoms[n] != null)
4624                     atoms[n].study(info);
4625                 minL2 = Math.min(minL2, info.minLength);
4626                 maxL2 = Math.max(maxL2, info.maxLength);
4627                 maxV = (maxV & info.maxValid);
4628             }
4629 
4630             minL += minL2;
4631             maxL += maxL2;
4632 
4633             info.reset();
4634             conn.next.study(info);
4635 
4636             info.minLength += minL;
4637             info.maxLength += maxL;
4638             info.maxValid &= maxV;
4639             info.deterministic = false;
4640             return false;
4641         }
4642     }
4643 
4644     /**
4645      * The GroupHead saves the location where the group begins in the locals
4646      * and restores them when the match is done.
4647      *
4648      * The matchRef is used when a reference to this group is accessed later
4649      * in the expression. The locals will have a negative value in them to
4650      * indicate that we do not want to unset the group if the reference
4651      * doesn't match.
4652      */
4653     static final class GroupHead extends Node {
4654         int localIndex;
4655         GroupHead(int localCount) {
4656             localIndex = localCount;
4657         }
4658         boolean match(Matcher matcher, int i, CharSequence seq) {
4659             int save = matcher.locals[localIndex];
4660             matcher.locals[localIndex] = i;
4661             boolean ret = next.match(matcher, i, seq);
4662             matcher.locals[localIndex] = save;
4663             return ret;
4664         }
4665         boolean matchRef(Matcher matcher, int i, CharSequence seq) {
4666             int save = matcher.locals[localIndex];
4667             matcher.locals[localIndex] = ~i; // HACK
4668             boolean ret = next.match(matcher, i, seq);
4669             matcher.locals[localIndex] = save;
4670             return ret;
4671         }
4672     }
4673 
4674     /**
4675      * Recursive reference to a group in the regular expression. It calls
4676      * matchRef because if the reference fails to match we would not unset
4677      * the group.
4678      */
4679     static final class GroupRef extends Node {
4680         GroupHead head;
4681         GroupRef(GroupHead head) {
4682             this.head = head;
4683         }
4684         boolean match(Matcher matcher, int i, CharSequence seq) {
4685             return head.matchRef(matcher, i, seq)
4686                 && next.match(matcher, matcher.last, seq);
4687         }
4688         boolean study(TreeInfo info) {
4689             info.maxValid = false;
4690             info.deterministic = false;
4691             return next.study(info);
4692         }
4693     }
4694 
4695     /**
4696      * The GroupTail handles the setting of group beginning and ending
4697      * locations when groups are successfully matched. It must also be able to
4698      * unset groups that have to be backed off of.
4699      *
4700      * The GroupTail node is also used when a previous group is referenced,
4701      * and in that case no group information needs to be set.
4702      */
4703     static final class GroupTail extends Node {
4704         int localIndex;
4705         int groupIndex;
4706         GroupTail(int localCount, int groupCount) {
4707             localIndex = localCount;
4708             groupIndex = groupCount + groupCount;
4709         }
4710         boolean match(Matcher matcher, int i, CharSequence seq) {
4711             int tmp = matcher.locals[localIndex];
4712             if (tmp >= 0) { // This is the normal group case.
4713                 // Save the group so we can unset it if it
4714                 // backs off of a match.
4715                 int groupStart = matcher.groups[groupIndex];
4716                 int groupEnd = matcher.groups[groupIndex+1];
4717 
4718                 matcher.groups[groupIndex] = tmp;
4719                 matcher.groups[groupIndex+1] = i;
4720                 if (next.match(matcher, i, seq)) {
4721                     return true;
4722                 }
4723                 matcher.groups[groupIndex] = groupStart;
4724                 matcher.groups[groupIndex+1] = groupEnd;
4725                 return false;
4726             } else {
4727                 // This is a group reference case. We don't need to save any
4728                 // group info because it isn't really a group.
4729                 matcher.last = i;
4730                 return true;
4731             }
4732         }
4733     }
4734 
4735     /**
4736      * This sets up a loop to handle a recursive quantifier structure.
4737      */
4738     static final class Prolog extends Node {
4739         Loop loop;
4740         Prolog(Loop loop) {
4741             this.loop = loop;
4742         }
4743         boolean match(Matcher matcher, int i, CharSequence seq) {
4744             return loop.matchInit(matcher, i, seq);
4745         }
4746         boolean study(TreeInfo info) {
4747             return loop.study(info);
4748         }
4749     }
4750 
4751     /**
4752      * Handles the repetition count for a greedy Curly. The matchInit
4753      * is called from the Prolog to save the index of where the group
4754      * beginning is stored. A zero length group check occurs in the
4755      * normal match but is skipped in the matchInit.
4756      */
4757     static class Loop extends Node {
4758         Node body;
4759         int countIndex; // local count index in matcher locals
4760         int beginIndex; // group beginning index
4761         int cmin, cmax;
4762         Loop(int countIndex, int beginIndex) {
4763             this.countIndex = countIndex;
4764             this.beginIndex = beginIndex;
4765         }
4766         boolean match(Matcher matcher, int i, CharSequence seq) {
4767             // Avoid infinite loop in zero-length case.
4768             if (i > matcher.locals[beginIndex]) {
4769                 int count = matcher.locals[countIndex];
4770 
4771                 // This block is for before we reach the minimum
4772                 // iterations required for the loop to match
4773                 if (count < cmin) {
4774                     matcher.locals[countIndex] = count + 1;
4775                     boolean b = body.match(matcher, i, seq);
4776                     // If match failed we must backtrack, so
4777                     // the loop count should NOT be incremented
4778                     if (!b)
4779                         matcher.locals[countIndex] = count;
4780                     // Return success or failure since we are under
4781                     // minimum
4782                     return b;
4783                 }
4784                 // This block is for after we have the minimum
4785                 // iterations required for the loop to match
4786                 if (count < cmax) {
4787                     matcher.locals[countIndex] = count + 1;
4788                     boolean b = body.match(matcher, i, seq);
4789                     // If match failed we must backtrack, so
4790                     // the loop count should NOT be incremented
4791                     if (!b)
4792                         matcher.locals[countIndex] = count;
4793                     else
4794                         return true;
4795                 }
4796             }
4797             return next.match(matcher, i, seq);
4798         }
4799         boolean matchInit(Matcher matcher, int i, CharSequence seq) {
4800             int save = matcher.locals[countIndex];
4801             boolean ret = false;
4802             if (0 < cmin) {
4803                 matcher.locals[countIndex] = 1;
4804                 ret = body.match(matcher, i, seq);
4805             } else if (0 < cmax) {
4806                 matcher.locals[countIndex] = 1;
4807                 ret = body.match(matcher, i, seq);
4808                 if (ret == false)
4809                     ret = next.match(matcher, i, seq);
4810             } else {
4811                 ret = next.match(matcher, i, seq);
4812             }
4813             matcher.locals[countIndex] = save;
4814             return ret;
4815         }
4816         boolean study(TreeInfo info) {
4817             info.maxValid = false;
4818             info.deterministic = false;
4819             return false;
4820         }
4821     }
4822 
4823     /**
4824      * Handles the repetition count for a reluctant Curly. The matchInit
4825      * is called from the Prolog to save the index of where the group
4826      * beginning is stored. A zero length group check occurs in the
4827      * normal match but is skipped in the matchInit.
4828      */
4829     static final class LazyLoop extends Loop {
4830         LazyLoop(int countIndex, int beginIndex) {
4831             super(countIndex, beginIndex);
4832         }
4833         boolean match(Matcher matcher, int i, CharSequence seq) {
4834             // Check for zero length group
4835             if (i > matcher.locals[beginIndex]) {
4836                 int count = matcher.locals[countIndex];
4837                 if (count < cmin) {
4838                     matcher.locals[countIndex] = count + 1;
4839                     boolean result = body.match(matcher, i, seq);
4840                     // If match failed we must backtrack, so
4841                     // the loop count should NOT be incremented
4842                     if (!result)
4843                         matcher.locals[countIndex] = count;
4844                     return result;
4845                 }
4846                 if (next.match(matcher, i, seq))
4847                     return true;
4848                 if (count < cmax) {
4849                     matcher.locals[countIndex] = count + 1;
4850                     boolean result = body.match(matcher, i, seq);
4851                     // If match failed we must backtrack, so
4852                     // the loop count should NOT be incremented
4853                     if (!result)
4854                         matcher.locals[countIndex] = count;
4855                     return result;
4856                 }
4857                 return false;
4858             }
4859             return next.match(matcher, i, seq);
4860         }
4861         boolean matchInit(Matcher matcher, int i, CharSequence seq) {
4862             int save = matcher.locals[countIndex];
4863             boolean ret = false;
4864             if (0 < cmin) {
4865                 matcher.locals[countIndex] = 1;
4866                 ret = body.match(matcher, i, seq);
4867             } else if (next.match(matcher, i, seq)) {
4868                 ret = true;
4869             } else if (0 < cmax) {
4870                 matcher.locals[countIndex] = 1;
4871                 ret = body.match(matcher, i, seq);
4872             }
4873             matcher.locals[countIndex] = save;
4874             return ret;
4875         }
4876         boolean study(TreeInfo info) {
4877             info.maxValid = false;
4878             info.deterministic = false;
4879             return false;
4880         }
4881     }
4882 
4883     /**
4884      * Refers to a group in the regular expression. Attempts to match
4885      * whatever the group referred to last matched.
4886      */
4887     static class BackRef extends Node {
4888         int groupIndex;
4889         BackRef(int groupCount) {
4890             super();
4891             groupIndex = groupCount + groupCount;
4892         }
4893         boolean match(Matcher matcher, int i, CharSequence seq) {
4894             int j = matcher.groups[groupIndex];
4895             int k = matcher.groups[groupIndex+1];
4896 
4897             int groupSize = k - j;
4898             // If the referenced group didn't match, neither can this
4899             if (j < 0)
4900                 return false;
4901 
4902             // If there isn't enough input left no match
4903             if (i + groupSize > matcher.to) {
4904                 matcher.hitEnd = true;
4905                 return false;
4906             }
4907             // Check each new char to make sure it matches what the group
4908             // referenced matched last time around
4909             for (int index=0; index<groupSize; index++)
4910                 if (seq.charAt(i+index) != seq.charAt(j+index))
4911                     return false;
4912 
4913             return next.match(matcher, i+groupSize, seq);
4914         }
4915         boolean study(TreeInfo info) {
4916             info.maxValid = false;
4917             return next.study(info);
4918         }
4919     }
4920 
4921     static class CIBackRef extends Node {
4922         int groupIndex;
4923         boolean doUnicodeCase;
4924         CIBackRef(int groupCount, boolean doUnicodeCase) {
4925             super();
4926             groupIndex = groupCount + groupCount;
4927             this.doUnicodeCase = doUnicodeCase;
4928         }
4929         boolean match(Matcher matcher, int i, CharSequence seq) {
4930             int j = matcher.groups[groupIndex];
4931             int k = matcher.groups[groupIndex+1];
4932 
4933             int groupSize = k - j;
4934 
4935             // If the referenced group didn't match, neither can this
4936             if (j < 0)
4937                 return false;
4938 
4939             // If there isn't enough input left no match
4940             if (i + groupSize > matcher.to) {
4941                 matcher.hitEnd = true;
4942                 return false;
4943             }
4944 
4945             // Check each new char to make sure it matches what the group
4946             // referenced matched last time around
4947             int x = i;
4948             for (int index=0; index<groupSize; index++) {
4949                 int c1 = Character.codePointAt(seq, x);
4950                 int c2 = Character.codePointAt(seq, j);
4951                 if (c1 != c2) {
4952                     if (doUnicodeCase) {
4953                         int cc1 = Character.toUpperCase(c1);
4954                         int cc2 = Character.toUpperCase(c2);
4955                         if (cc1 != cc2 &&
4956                             Character.toLowerCase(cc1) !=
4957                             Character.toLowerCase(cc2))
4958                             return false;
4959                     } else {
4960                         if (ASCII.toLower(c1) != ASCII.toLower(c2))
4961                             return false;
4962                     }
4963                 }
4964                 x += Character.charCount(c1);
4965                 j += Character.charCount(c2);
4966             }
4967 
4968             return next.match(matcher, i+groupSize, seq);
4969         }
4970         boolean study(TreeInfo info) {
4971             info.maxValid = false;
4972             return next.study(info);
4973         }
4974     }
4975 
4976     /**
4977      * Searches until the next instance of its atom. This is useful for
4978      * finding the atom efficiently without passing an instance of it
4979      * (greedy problem) and without a lot of wasted search time (reluctant
4980      * problem).
4981      */
4982     static final class First extends Node {
4983         Node atom;
4984         First(Node node) {
4985             this.atom = BnM.optimize(node);
4986         }
4987         boolean match(Matcher matcher, int i, CharSequence seq) {
4988             if (atom instanceof BnM) {
4989                 return atom.match(matcher, i, seq)
4990                     && next.match(matcher, matcher.last, seq);
4991             }
4992             for (;;) {
4993                 if (i > matcher.to) {
4994                     matcher.hitEnd = true;
4995                     return false;
4996                 }
4997                 if (atom.match(matcher, i, seq)) {
4998                     return next.match(matcher, matcher.last, seq);
4999                 }
5000                 i += countChars(seq, i, 1);
5001                 matcher.first++;
5002             }
5003         }
5004         boolean study(TreeInfo info) {
5005             atom.study(info);
5006             info.maxValid = false;
5007             info.deterministic = false;
5008             return next.study(info);
5009         }
5010     }
5011 
5012     static final class Conditional extends Node {
5013         Node cond, yes, not;
5014         Conditional(Node cond, Node yes, Node not) {
5015             this.cond = cond;
5016             this.yes = yes;
5017             this.not = not;
5018         }
5019         boolean match(Matcher matcher, int i, CharSequence seq) {
5020             if (cond.match(matcher, i, seq)) {
5021                 return yes.match(matcher, i, seq);
5022             } else {
5023                 return not.match(matcher, i, seq);
5024             }
5025         }
5026         boolean study(TreeInfo info) {
5027             int minL = info.minLength;
5028             int maxL = info.maxLength;
5029             boolean maxV = info.maxValid;
5030             info.reset();
5031             yes.study(info);
5032 
5033             int minL2 = info.minLength;
5034             int maxL2 = info.maxLength;
5035             boolean maxV2 = info.maxValid;
5036             info.reset();
5037             not.study(info);
5038 
5039             info.minLength = minL + Math.min(minL2, info.minLength);
5040             info.maxLength = maxL + Math.max(maxL2, info.maxLength);
5041             info.maxValid = (maxV & maxV2 & info.maxValid);
5042             info.deterministic = false;
5043             return next.study(info);
5044         }
5045     }
5046 
5047     /**
5048      * Zero width positive lookahead.
5049      */
5050     static final class Pos extends Node {
5051         Node cond;
5052         Pos(Node cond) {
5053             this.cond = cond;
5054         }
5055         boolean match(Matcher matcher, int i, CharSequence seq) {
5056             int savedTo = matcher.to;
5057             boolean conditionMatched = false;
5058 
5059             // Relax transparent region boundaries for lookahead
5060             if (matcher.transparentBounds)
5061                 matcher.to = matcher.getTextLength();
5062             try {
5063                 conditionMatched = cond.match(matcher, i, seq);
5064             } finally {
5065                 // Reinstate region boundaries
5066                 matcher.to = savedTo;
5067             }
5068             return conditionMatched && next.match(matcher, i, seq);
5069         }
5070     }
5071 
5072     /**
5073      * Zero width negative lookahead.
5074      */
5075     static final class Neg extends Node {
5076         Node cond;
5077         Neg(Node cond) {
5078             this.cond = cond;
5079         }
5080         boolean match(Matcher matcher, int i, CharSequence seq) {
5081             int savedTo = matcher.to;
5082             boolean conditionMatched = false;
5083 
5084             // Relax transparent region boundaries for lookahead
5085             if (matcher.transparentBounds)
5086                 matcher.to = matcher.getTextLength();
5087             try {
5088                 if (i < matcher.to) {
5089                     conditionMatched = !cond.match(matcher, i, seq);
5090                 } else {
5091                     // If a negative lookahead succeeds then more input
5092                     // could cause it to fail!
5093                     matcher.requireEnd = true;
5094                     conditionMatched = !cond.match(matcher, i, seq);
5095                 }
5096             } finally {
5097                 // Reinstate region boundaries
5098                 matcher.to = savedTo;
5099             }
5100             return conditionMatched && next.match(matcher, i, seq);
5101         }
5102     }
5103 
5104     /**
5105      * For use with lookbehinds; matches the position where the lookbehind
5106      * was encountered.
5107      */
5108     static Node lookbehindEnd = new Node() {
5109         boolean match(Matcher matcher, int i, CharSequence seq) {
5110             return i == matcher.lookbehindTo;
5111         }
5112     };
5113 
5114     /**
5115      * Zero width positive lookbehind.
5116      */
5117     static class Behind extends Node {
5118         Node cond;
5119         int rmax, rmin;
5120         Behind(Node cond, int rmax, int rmin) {
5121             this.cond = cond;
5122             this.rmax = rmax;
5123             this.rmin = rmin;
5124         }
5125 
5126         boolean match(Matcher matcher, int i, CharSequence seq) {
5127             int savedFrom = matcher.from;
5128             boolean conditionMatched = false;
5129             int startIndex = (!matcher.transparentBounds) ?
5130                              matcher.from : 0;
5131             int from = Math.max(i - rmax, startIndex);
5132             // Set end boundary
5133             int savedLBT = matcher.lookbehindTo;
5134             matcher.lookbehindTo = i;
5135             // Relax transparent region boundaries for lookbehind
5136             if (matcher.transparentBounds)
5137                 matcher.from = 0;
5138             for (int j = i - rmin; !conditionMatched && j >= from; j--) {
5139                 conditionMatched = cond.match(matcher, j, seq);
5140             }
5141             matcher.from = savedFrom;
5142             matcher.lookbehindTo = savedLBT;
5143             return conditionMatched && next.match(matcher, i, seq);
5144         }
5145     }
5146 
5147     /**
5148      * Zero width positive lookbehind, including supplementary
5149      * characters or unpaired surrogates.
5150      */
5151     static final class BehindS extends Behind {
5152         BehindS(Node cond, int rmax, int rmin) {
5153             super(cond, rmax, rmin);
5154         }
5155         boolean match(Matcher matcher, int i, CharSequence seq) {
5156             int rmaxChars = countChars(seq, i, -rmax);
5157             int rminChars = countChars(seq, i, -rmin);
5158             int savedFrom = matcher.from;
5159             int startIndex = (!matcher.transparentBounds) ?
5160                              matcher.from : 0;
5161             boolean conditionMatched = false;
5162             int from = Math.max(i - rmaxChars, startIndex);
5163             // Set end boundary
5164             int savedLBT = matcher.lookbehindTo;
5165             matcher.lookbehindTo = i;
5166             // Relax transparent region boundaries for lookbehind
5167             if (matcher.transparentBounds)
5168                 matcher.from = 0;
5169 
5170             for (int j = i - rminChars;
5171                  !conditionMatched && j >= from;
5172                  j -= j>from ? countChars(seq, j, -1) : 1) {
5173                 conditionMatched = cond.match(matcher, j, seq);
5174             }
5175             matcher.from = savedFrom;
5176             matcher.lookbehindTo = savedLBT;
5177             return conditionMatched && next.match(matcher, i, seq);
5178         }
5179     }
5180 
5181     /**
5182      * Zero width negative lookbehind.
5183      */
5184     static class NotBehind extends Node {
5185         Node cond;
5186         int rmax, rmin;
5187         NotBehind(Node cond, int rmax, int rmin) {
5188             this.cond = cond;
5189             this.rmax = rmax;
5190             this.rmin = rmin;
5191         }
5192 
5193         boolean match(Matcher matcher, int i, CharSequence seq) {
5194             int savedLBT = matcher.lookbehindTo;
5195             int savedFrom = matcher.from;
5196             boolean conditionMatched = false;
5197             int startIndex = (!matcher.transparentBounds) ?
5198                              matcher.from : 0;
5199             int from = Math.max(i - rmax, startIndex);
5200             matcher.lookbehindTo = i;
5201             // Relax transparent region boundaries for lookbehind
5202             if (matcher.transparentBounds)
5203                 matcher.from = 0;
5204             for (int j = i - rmin; !conditionMatched && j >= from; j--) {
5205                 conditionMatched = cond.match(matcher, j, seq);
5206             }
5207             // Reinstate region boundaries
5208             matcher.from = savedFrom;
5209             matcher.lookbehindTo = savedLBT;
5210             return !conditionMatched && next.match(matcher, i, seq);
5211         }
5212     }
5213 
5214     /**
5215      * Zero width negative lookbehind, including supplementary
5216      * characters or unpaired surrogates.
5217      */
5218     static final class NotBehindS extends NotBehind {
5219         NotBehindS(Node cond, int rmax, int rmin) {
5220             super(cond, rmax, rmin);
5221         }
5222         boolean match(Matcher matcher, int i, CharSequence seq) {
5223             int rmaxChars = countChars(seq, i, -rmax);
5224             int rminChars = countChars(seq, i, -rmin);
5225             int savedFrom = matcher.from;
5226             int savedLBT = matcher.lookbehindTo;
5227             boolean conditionMatched = false;
5228             int startIndex = (!matcher.transparentBounds) ?
5229                              matcher.from : 0;
5230             int from = Math.max(i - rmaxChars, startIndex);
5231             matcher.lookbehindTo = i;
5232             // Relax transparent region boundaries for lookbehind
5233             if (matcher.transparentBounds)
5234                 matcher.from = 0;
5235             for (int j = i - rminChars;
5236                  !conditionMatched && j >= from;
5237                  j -= j>from ? countChars(seq, j, -1) : 1) {
5238                 conditionMatched = cond.match(matcher, j, seq);
5239             }
5240             //Reinstate region boundaries
5241             matcher.from = savedFrom;
5242             matcher.lookbehindTo = savedLBT;
5243             return !conditionMatched && next.match(matcher, i, seq);
5244         }
5245     }
5246 
5247     /**
5248      * Returns the set union of two CharProperty nodes.
5249      */
5250     private static CharProperty union(final CharProperty lhs,
5251                                       final CharProperty rhs) {
5252         return new CharProperty() {
5253                 boolean isSatisfiedBy(int ch) {
5254                     return lhs.isSatisfiedBy(ch) || rhs.isSatisfiedBy(ch);}};
5255     }
5256 
5257     /**
5258      * Returns the set intersection of two CharProperty nodes.
5259      */
5260     private static CharProperty intersection(final CharProperty lhs,
5261                                              final CharProperty rhs) {
5262         return new CharProperty() {
5263                 boolean isSatisfiedBy(int ch) {
5264                     return lhs.isSatisfiedBy(ch) && rhs.isSatisfiedBy(ch);}};
5265     }
5266 
5267     /**
5268      * Returns the set difference of two CharProperty nodes.
5269      */
5270     private static CharProperty setDifference(final CharProperty lhs,
5271                                               final CharProperty rhs) {
5272         return new CharProperty() {
5273                 boolean isSatisfiedBy(int ch) {
5274                     return ! rhs.isSatisfiedBy(ch) && lhs.isSatisfiedBy(ch);}};
5275     }
5276 
5277     /**
5278      * Handles word boundaries. Includes a field to allow this one class to
5279      * deal with the different types of word boundaries we can match. The word
5280      * characters include underscores, letters, and digits. Non spacing marks
5281      * can are also part of a word if they have a base character, otherwise
5282      * they are ignored for purposes of finding word boundaries.
5283      */
5284     static final class Bound extends Node {
5285         static int LEFT = 0x1;
5286         static int RIGHT= 0x2;
5287         static int BOTH = 0x3;
5288         static int NONE = 0x4;
5289         int type;
5290         boolean useUWORD;
5291         Bound(int n, boolean useUWORD) {
5292             type = n;
5293             this.useUWORD = useUWORD;
5294         }
5295 
5296         boolean isWord(int ch) {
5297             return useUWORD ? UnicodeProp.WORD.is(ch)
5298                             : (ch == '_' || Character.isLetterOrDigit(ch));
5299         }
5300 
5301         int check(Matcher matcher, int i, CharSequence seq) {
5302             int ch;
5303             boolean left = false;
5304             int startIndex = matcher.from;
5305             int endIndex = matcher.to;
5306             if (matcher.transparentBounds) {
5307                 startIndex = 0;
5308                 endIndex = matcher.getTextLength();
5309             }
5310             if (i > startIndex) {
5311                 ch = Character.codePointBefore(seq, i);
5312                 left = (isWord(ch) ||
5313                     ((Character.getType(ch) == Character.NON_SPACING_MARK)
5314                      && hasBaseCharacter(matcher, i-1, seq)));
5315             }
5316             boolean right = false;
5317             if (i < endIndex) {
5318                 ch = Character.codePointAt(seq, i);
5319                 right = (isWord(ch) ||
5320                     ((Character.getType(ch) == Character.NON_SPACING_MARK)
5321                      && hasBaseCharacter(matcher, i, seq)));
5322             } else {
5323                 // Tried to access char past the end
5324                 matcher.hitEnd = true;
5325                 // The addition of another char could wreck a boundary
5326                 matcher.requireEnd = true;
5327             }
5328             return ((left ^ right) ? (right ? LEFT : RIGHT) : NONE);
5329         }
5330         boolean match(Matcher matcher, int i, CharSequence seq) {
5331             return (check(matcher, i, seq) & type) > 0
5332                 && next.match(matcher, i, seq);
5333         }
5334     }
5335 
5336     /**
5337      * Non spacing marks only count as word characters in bounds calculations
5338      * if they have a base character.
5339      */
5340     private static boolean hasBaseCharacter(Matcher matcher, int i,
5341                                             CharSequence seq)
5342     {
5343         int start = (!matcher.transparentBounds) ?
5344             matcher.from : 0;
5345         for (int x=i; x >= start; x--) {
5346             int ch = Character.codePointAt(seq, x);
5347             if (Character.isLetterOrDigit(ch))
5348                 return true;
5349             if (Character.getType(ch) == Character.NON_SPACING_MARK)
5350                 continue;
5351             return false;
5352         }
5353         return false;
5354     }
5355 
5356     /**
5357      * Attempts to match a slice in the input using the Boyer-Moore string
5358      * matching algorithm. The algorithm is based on the idea that the
5359      * pattern can be shifted farther ahead in the search text if it is
5360      * matched right to left.
5361      * <p>
5362      * The pattern is compared to the input one character at a time, from
5363      * the rightmost character in the pattern to the left. If the characters
5364      * all match the pattern has been found. If a character does not match,
5365      * the pattern is shifted right a distance that is the maximum of two
5366      * functions, the bad character shift and the good suffix shift. This
5367      * shift moves the attempted match position through the input more
5368      * quickly than a naive one position at a time check.
5369      * <p>
5370      * The bad character shift is based on the character from the text that
5371      * did not match. If the character does not appear in the pattern, the
5372      * pattern can be shifted completely beyond the bad character. If the
5373      * character does occur in the pattern, the pattern can be shifted to
5374      * line the pattern up with the next occurrence of that character.
5375      * <p>
5376      * The good suffix shift is based on the idea that some subset on the right
5377      * side of the pattern has matched. When a bad character is found, the
5378      * pattern can be shifted right by the pattern length if the subset does
5379      * not occur again in pattern, or by the amount of distance to the
5380      * next occurrence of the subset in the pattern.
5381      *
5382      * Boyer-Moore search methods adapted from code by Amy Yu.
5383      */
5384     static class BnM extends Node {
5385         int[] buffer;
5386         int[] lastOcc;
5387         int[] optoSft;
5388 
5389         /**
5390          * Pre calculates arrays needed to generate the bad character
5391          * shift and the good suffix shift. Only the last seven bits
5392          * are used to see if chars match; This keeps the tables small
5393          * and covers the heavily used ASCII range, but occasionally
5394          * results in an aliased match for the bad character shift.
5395          */
5396         static Node optimize(Node node) {
5397             if (!(node instanceof Slice)) {
5398                 return node;
5399             }
5400 
5401             int[] src = ((Slice) node).buffer;
5402             int patternLength = src.length;
5403             // The BM algorithm requires a bit of overhead;
5404             // If the pattern is short don't use it, since
5405             // a shift larger than the pattern length cannot
5406             // be used anyway.
5407             if (patternLength < 4) {
5408                 return node;
5409             }
5410             int i, j, k;
5411             int[] lastOcc = new int[128];
5412             int[] optoSft = new int[patternLength];
5413             // Precalculate part of the bad character shift
5414             // It is a table for where in the pattern each
5415             // lower 7-bit value occurs
5416             for (i = 0; i < patternLength; i++) {
5417                 lastOcc[src[i]&0x7F] = i + 1;
5418             }
5419             // Precalculate the good suffix shift
5420             // i is the shift amount being considered
5421 NEXT:       for (i = patternLength; i > 0; i--) {
5422                 // j is the beginning index of suffix being considered
5423                 for (j = patternLength - 1; j >= i; j--) {
5424                     // Testing for good suffix
5425                     if (src[j] == src[j-i]) {
5426                         // src[j..len] is a good suffix
5427                         optoSft[j-1] = i;
5428                     } else {
5429                         // No match. The array has already been
5430                         // filled up with correct values before.
5431                         continue NEXT;
5432                     }
5433                 }
5434                 // This fills up the remaining of optoSft
5435                 // any suffix can not have larger shift amount
5436                 // then its sub-suffix. Why???
5437                 while (j > 0) {
5438                     optoSft[--j] = i;
5439                 }
5440             }
5441             // Set the guard value because of unicode compression
5442             optoSft[patternLength-1] = 1;
5443             if (node instanceof SliceS)
5444                 return new BnMS(src, lastOcc, optoSft, node.next);
5445             return new BnM(src, lastOcc, optoSft, node.next);
5446         }
5447         BnM(int[] src, int[] lastOcc, int[] optoSft, Node next) {
5448             this.buffer = src;
5449             this.lastOcc = lastOcc;
5450             this.optoSft = optoSft;
5451             this.next = next;
5452         }
5453         boolean match(Matcher matcher, int i, CharSequence seq) {
5454             int[] src = buffer;
5455             int patternLength = src.length;
5456             int last = matcher.to - patternLength;
5457 
5458             // Loop over all possible match positions in text
5459 NEXT:       while (i <= last) {
5460                 // Loop over pattern from right to left
5461                 for (int j = patternLength - 1; j >= 0; j--) {
5462                     int ch = seq.charAt(i+j);
5463                     if (ch != src[j]) {
5464                         // Shift search to the right by the maximum of the
5465                         // bad character shift and the good suffix shift
5466                         i += Math.max(j + 1 - lastOcc[ch&0x7F], optoSft[j]);
5467                         continue NEXT;
5468                     }
5469                 }
5470                 // Entire pattern matched starting at i
5471                 matcher.first = i;
5472                 boolean ret = next.match(matcher, i + patternLength, seq);
5473                 if (ret) {
5474                     matcher.first = i;
5475                     matcher.groups[0] = matcher.first;
5476                     matcher.groups[1] = matcher.last;
5477                     return true;
5478                 }
5479                 i++;
5480             }
5481             // BnM is only used as the leading node in the unanchored case,
5482             // and it replaced its Start() which always searches to the end
5483             // if it doesn't find what it's looking for, so hitEnd is true.
5484             matcher.hitEnd = true;
5485             return false;
5486         }
5487         boolean study(TreeInfo info) {
5488             info.minLength += buffer.length;
5489             info.maxValid = false;
5490             return next.study(info);
5491         }
5492     }
5493 
5494     /**
5495      * Supplementary support version of BnM(). Unpaired surrogates are
5496      * also handled by this class.
5497      */
5498     static final class BnMS extends BnM {
5499         int lengthInChars;
5500 
5501         BnMS(int[] src, int[] lastOcc, int[] optoSft, Node next) {
5502             super(src, lastOcc, optoSft, next);
5503             for (int x = 0; x < buffer.length; x++) {
5504                 lengthInChars += Character.charCount(buffer[x]);
5505             }
5506         }
5507         boolean match(Matcher matcher, int i, CharSequence seq) {
5508             int[] src = buffer;
5509             int patternLength = src.length;
5510             int last = matcher.to - lengthInChars;
5511 
5512             // Loop over all possible match positions in text
5513 NEXT:       while (i <= last) {
5514                 // Loop over pattern from right to left
5515                 int ch;
5516                 for (int j = countChars(seq, i, patternLength), x = patternLength - 1;
5517                      j > 0; j -= Character.charCount(ch), x--) {
5518                     ch = Character.codePointBefore(seq, i+j);
5519                     if (ch != src[x]) {
5520                         // Shift search to the right by the maximum of the
5521                         // bad character shift and the good suffix shift
5522                         int n = Math.max(x + 1 - lastOcc[ch&0x7F], optoSft[x]);
5523                         i += countChars(seq, i, n);
5524                         continue NEXT;
5525                     }
5526                 }
5527                 // Entire pattern matched starting at i
5528                 matcher.first = i;
5529                 boolean ret = next.match(matcher, i + lengthInChars, seq);
5530                 if (ret) {
5531                     matcher.first = i;
5532                     matcher.groups[0] = matcher.first;
5533                     matcher.groups[1] = matcher.last;
5534                     return true;
5535                 }
5536                 i += countChars(seq, i, 1);
5537             }
5538             matcher.hitEnd = true;
5539             return false;
5540         }
5541     }
5542 
5543 ///////////////////////////////////////////////////////////////////////////////
5544 ///////////////////////////////////////////////////////////////////////////////
5545 
5546     /**
5547      *  This must be the very first initializer.
5548      */
5549     static Node accept = new Node();
5550 
5551     static Node lastAccept = new LastNode();
5552 
5553     private static class CharPropertyNames {
5554 
5555         static CharProperty charPropertyFor(String name) {
5556             CharPropertyFactory m = map.get(name);
5557             return m == null ? null : m.make();
5558         }
5559 
5560         private static abstract class CharPropertyFactory {
5561             abstract CharProperty make();
5562         }
5563 
5564         private static void defCategory(String name,
5565                                         final int typeMask) {
5566             map.put(name, new CharPropertyFactory() {
5567                     CharProperty make() { return new Category(typeMask);}});
5568         }
5569 
5570         private static void defRange(String name,
5571                                      final int lower, final int upper) {
5572             map.put(name, new CharPropertyFactory() {
5573                     CharProperty make() { return rangeFor(lower, upper);}});
5574         }
5575 
5576         private static void defCtype(String name,
5577                                      final int ctype) {
5578             map.put(name, new CharPropertyFactory() {
5579                     CharProperty make() { return new Ctype(ctype);}});
5580         }
5581 
5582         private static abstract class CloneableProperty
5583             extends CharProperty implements Cloneable
5584         {
5585             public CloneableProperty clone() {
5586                 try {
5587                     return (CloneableProperty) super.clone();
5588                 } catch (CloneNotSupportedException e) {
5589                     throw new AssertionError(e);
5590                 }
5591             }
5592         }
5593 
5594         private static void defClone(String name,
5595                                      final CloneableProperty p) {
5596             map.put(name, new CharPropertyFactory() {
5597                     CharProperty make() { return p.clone();}});
5598         }
5599 
5600         private static final HashMap<String, CharPropertyFactory> map
5601             = new HashMap<>();
5602 
5603         static {
5604             // Unicode character property aliases, defined in
5605             // http://www.unicode.org/Public/UNIDATA/PropertyValueAliases.txt
5606             defCategory("Cn", 1<<Character.UNASSIGNED);
5607             defCategory("Lu", 1<<Character.UPPERCASE_LETTER);
5608             defCategory("Ll", 1<<Character.LOWERCASE_LETTER);
5609             defCategory("Lt", 1<<Character.TITLECASE_LETTER);
5610             defCategory("Lm", 1<<Character.MODIFIER_LETTER);
5611             defCategory("Lo", 1<<Character.OTHER_LETTER);
5612             defCategory("Mn", 1<<Character.NON_SPACING_MARK);
5613             defCategory("Me", 1<<Character.ENCLOSING_MARK);
5614             defCategory("Mc", 1<<Character.COMBINING_SPACING_MARK);
5615             defCategory("Nd", 1<<Character.DECIMAL_DIGIT_NUMBER);
5616             defCategory("Nl", 1<<Character.LETTER_NUMBER);
5617             defCategory("No", 1<<Character.OTHER_NUMBER);
5618             defCategory("Zs", 1<<Character.SPACE_SEPARATOR);
5619             defCategory("Zl", 1<<Character.LINE_SEPARATOR);
5620             defCategory("Zp", 1<<Character.PARAGRAPH_SEPARATOR);
5621             defCategory("Cc", 1<<Character.CONTROL);
5622             defCategory("Cf", 1<<Character.FORMAT);
5623             defCategory("Co", 1<<Character.PRIVATE_USE);
5624             defCategory("Cs", 1<<Character.SURROGATE);
5625             defCategory("Pd", 1<<Character.DASH_PUNCTUATION);
5626             defCategory("Ps", 1<<Character.START_PUNCTUATION);
5627             defCategory("Pe", 1<<Character.END_PUNCTUATION);
5628             defCategory("Pc", 1<<Character.CONNECTOR_PUNCTUATION);
5629             defCategory("Po", 1<<Character.OTHER_PUNCTUATION);
5630             defCategory("Sm", 1<<Character.MATH_SYMBOL);
5631             defCategory("Sc", 1<<Character.CURRENCY_SYMBOL);
5632             defCategory("Sk", 1<<Character.MODIFIER_SYMBOL);
5633             defCategory("So", 1<<Character.OTHER_SYMBOL);
5634             defCategory("Pi", 1<<Character.INITIAL_QUOTE_PUNCTUATION);
5635             defCategory("Pf", 1<<Character.FINAL_QUOTE_PUNCTUATION);
5636             defCategory("L", ((1<<Character.UPPERCASE_LETTER) |
5637                               (1<<Character.LOWERCASE_LETTER) |
5638                               (1<<Character.TITLECASE_LETTER) |
5639                               (1<<Character.MODIFIER_LETTER)  |
5640                               (1<<Character.OTHER_LETTER)));
5641             defCategory("M", ((1<<Character.NON_SPACING_MARK) |
5642                               (1<<Character.ENCLOSING_MARK)   |
5643                               (1<<Character.COMBINING_SPACING_MARK)));
5644             defCategory("N", ((1<<Character.DECIMAL_DIGIT_NUMBER) |
5645                               (1<<Character.LETTER_NUMBER)        |
5646                               (1<<Character.OTHER_NUMBER)));
5647             defCategory("Z", ((1<<Character.SPACE_SEPARATOR) |
5648                               (1<<Character.LINE_SEPARATOR)  |
5649                               (1<<Character.PARAGRAPH_SEPARATOR)));
5650             defCategory("C", ((1<<Character.CONTROL)     |
5651                               (1<<Character.FORMAT)      |
5652                               (1<<Character.PRIVATE_USE) |
5653                               (1<<Character.SURROGATE))); // Other
5654             defCategory("P", ((1<<Character.DASH_PUNCTUATION)      |
5655                               (1<<Character.START_PUNCTUATION)     |
5656                               (1<<Character.END_PUNCTUATION)       |
5657                               (1<<Character.CONNECTOR_PUNCTUATION) |
5658                               (1<<Character.OTHER_PUNCTUATION)     |
5659                               (1<<Character.INITIAL_QUOTE_PUNCTUATION) |
5660                               (1<<Character.FINAL_QUOTE_PUNCTUATION)));
5661             defCategory("S", ((1<<Character.MATH_SYMBOL)     |
5662                               (1<<Character.CURRENCY_SYMBOL) |
5663                               (1<<Character.MODIFIER_SYMBOL) |
5664                               (1<<Character.OTHER_SYMBOL)));
5665             defCategory("LC", ((1<<Character.UPPERCASE_LETTER) |
5666                                (1<<Character.LOWERCASE_LETTER) |
5667                                (1<<Character.TITLECASE_LETTER)));
5668             defCategory("LD", ((1<<Character.UPPERCASE_LETTER) |
5669                                (1<<Character.LOWERCASE_LETTER) |
5670                                (1<<Character.TITLECASE_LETTER) |
5671                                (1<<Character.MODIFIER_LETTER)  |
5672                                (1<<Character.OTHER_LETTER)     |
5673                                (1<<Character.DECIMAL_DIGIT_NUMBER)));
5674             defRange("L1", 0x00, 0xFF); // Latin-1
5675             map.put("all", new CharPropertyFactory() {
5676                     CharProperty make() { return new All(); }});
5677 
5678             // Posix regular expression character classes, defined in
5679             // http://www.unix.org/onlinepubs/009695399/basedefs/xbd_chap09.html
5680             defRange("ASCII", 0x00, 0x7F);   // ASCII
5681             defCtype("Alnum", ASCII.ALNUM);  // Alphanumeric characters
5682             defCtype("Alpha", ASCII.ALPHA);  // Alphabetic characters
5683             defCtype("Blank", ASCII.BLANK);  // Space and tab characters
5684             defCtype("Cntrl", ASCII.CNTRL);  // Control characters
5685             defRange("Digit", '0', '9');     // Numeric characters
5686             defCtype("Graph", ASCII.GRAPH);  // printable and visible
5687             defRange("Lower", 'a', 'z');     // Lower-case alphabetic
5688             defRange("Print", 0x20, 0x7E);   // Printable characters
5689             defCtype("Punct", ASCII.PUNCT);  // Punctuation characters
5690             defCtype("Space", ASCII.SPACE);  // Space characters
5691             defRange("Upper", 'A', 'Z');     // Upper-case alphabetic
5692             defCtype("XDigit",ASCII.XDIGIT); // hexadecimal digits
5693 
5694             // Java character properties, defined by methods in Character.java
5695             defClone("javaLowerCase", new CloneableProperty() {
5696                 boolean isSatisfiedBy(int ch) {
5697                     return Character.isLowerCase(ch);}});
5698             defClone("javaUpperCase", new CloneableProperty() {
5699                 boolean isSatisfiedBy(int ch) {
5700                     return Character.isUpperCase(ch);}});
5701             defClone("javaAlphabetic", new CloneableProperty() {
5702                 boolean isSatisfiedBy(int ch) {
5703                     return Character.isAlphabetic(ch);}});
5704             defClone("javaIdeographic", new CloneableProperty() {
5705                 boolean isSatisfiedBy(int ch) {
5706                     return Character.isIdeographic(ch);}});
5707             defClone("javaTitleCase", new CloneableProperty() {
5708                 boolean isSatisfiedBy(int ch) {
5709                     return Character.isTitleCase(ch);}});
5710             defClone("javaDigit", new CloneableProperty() {
5711                 boolean isSatisfiedBy(int ch) {
5712                     return Character.isDigit(ch);}});
5713             defClone("javaDefined", new CloneableProperty() {
5714                 boolean isSatisfiedBy(int ch) {
5715                     return Character.isDefined(ch);}});
5716             defClone("javaLetter", new CloneableProperty() {
5717                 boolean isSatisfiedBy(int ch) {
5718                     return Character.isLetter(ch);}});
5719             defClone("javaLetterOrDigit", new CloneableProperty() {
5720                 boolean isSatisfiedBy(int ch) {
5721                     return Character.isLetterOrDigit(ch);}});
5722             defClone("javaJavaIdentifierStart", new CloneableProperty() {
5723                 boolean isSatisfiedBy(int ch) {
5724                     return Character.isJavaIdentifierStart(ch);}});
5725             defClone("javaJavaIdentifierPart", new CloneableProperty() {
5726                 boolean isSatisfiedBy(int ch) {
5727                     return Character.isJavaIdentifierPart(ch);}});
5728             defClone("javaUnicodeIdentifierStart", new CloneableProperty() {
5729                 boolean isSatisfiedBy(int ch) {
5730                     return Character.isUnicodeIdentifierStart(ch);}});
5731             defClone("javaUnicodeIdentifierPart", new CloneableProperty() {
5732                 boolean isSatisfiedBy(int ch) {
5733                     return Character.isUnicodeIdentifierPart(ch);}});
5734             defClone("javaIdentifierIgnorable", new CloneableProperty() {
5735                 boolean isSatisfiedBy(int ch) {
5736                     return Character.isIdentifierIgnorable(ch);}});
5737             defClone("javaSpaceChar", new CloneableProperty() {
5738                 boolean isSatisfiedBy(int ch) {
5739                     return Character.isSpaceChar(ch);}});
5740             defClone("javaWhitespace", new CloneableProperty() {
5741                 boolean isSatisfiedBy(int ch) {
5742                     return Character.isWhitespace(ch);}});
5743             defClone("javaISOControl", new CloneableProperty() {
5744                 boolean isSatisfiedBy(int ch) {
5745                     return Character.isISOControl(ch);}});
5746             defClone("javaMirrored", new CloneableProperty() {
5747                 boolean isSatisfiedBy(int ch) {
5748                     return Character.isMirrored(ch);}});
5749         }
5750     }
5751 
5752     /**
5753      * Creates a predicate which can be used to match a string.
5754      *
5755      * @return  The predicate which can be used for matching on a string
5756      * @since   1.8
5757      */
5758     public Predicate<String> asPredicate() {
5759         return s -> matcher(s).find();
5760     }
5761 
5762     /**
5763      * Creates a stream from the given input sequence around matches of this
5764      * pattern.
5765      *
5766      * <p> The stream returned by this method contains each substring of the
5767      * input sequence that is terminated by another subsequence that matches
5768      * this pattern or is terminated by the end of the input sequence.  The
5769      * substrings in the stream are in the order in which they occur in the
5770      * input.  Trailing empty strings will be discarded and not encountered in
5771      * the stream.
5772      *
5773      * <p> If this pattern does not match any subsequence of the input then
5774      * the resulting stream has just one element, namely the input sequence in
5775      * string form.
5776      *
5777      * <p> A zero-length input sequence always results an empty stream.
5778      *
5779      * <p> When there is a positive-width match at the beginning of the input
5780      * sequence then an empty leading substring is included at the beginning
5781      * of the stream. A zero-width match at the beginning however never produces
5782      * such empty leading substring.
5783      *
5784      * <p> If the input sequence is mutable, it must remain constant during the
5785      * execution of the terminal stream operation.  Otherwise, the result of the
5786      * terminal stream operation is undefined.
5787      *
5788      * @param   input
5789      *          The character sequence to be split
5790      *
5791      * @return  The stream of strings computed by splitting the input
5792      *          around matches of this pattern
5793      * @see     #split(CharSequence)
5794      * @since   1.8
5795      */
5796     public Stream<String> splitAsStream(final CharSequence input) {
5797         class MatcherIterator implements Iterator<String> {
5798             private final Matcher matcher;
5799             // The start position of the next sub-sequence of input
5800             // when current == input.length there are no more elements
5801             private int current;
5802             // null if the next element, if any, needs to obtained
5803             private String nextElement;
5804             // > 0 if there are N next empty elements
5805             private int emptyElementCount;
5806 
5807             MatcherIterator() {
5808                 this.matcher = matcher(input);
5809             }
5810 
5811             public String next() {
5812                 if (!hasNext())
5813                     throw new NoSuchElementException();
5814 
5815                 if (emptyElementCount == 0) {
5816                     String n = nextElement;
5817                     nextElement = null;
5818                     return n;
5819                 } else {
5820                     emptyElementCount--;
5821                     return "";
5822                 }
5823             }
5824 
5825             public boolean hasNext() {
5826                 if (nextElement != null || emptyElementCount > 0)
5827                     return true;
5828 
5829                 if (current == input.length())
5830                     return false;
5831 
5832                 // Consume the next matching element
5833                 // Count sequence of matching empty elements
5834                 while (matcher.find()) {
5835                     nextElement = input.subSequence(current, matcher.start()).toString();
5836                     current = matcher.end();
5837                     if (!nextElement.isEmpty()) {
5838                         return true;
5839                     } else if (current > 0) { // no empty leading substring for zero-width
5840                                               // match at the beginning of the input
5841                         emptyElementCount++;
5842                     }
5843                 }
5844 
5845                 // Consume last matching element
5846                 nextElement = input.subSequence(current, input.length()).toString();
5847                 current = input.length();
5848                 if (!nextElement.isEmpty()) {
5849                     return true;
5850                 } else {
5851                     // Ignore a terminal sequence of matching empty elements
5852                     emptyElementCount = 0;
5853                     nextElement = null;
5854                     return false;
5855                 }
5856             }
5857         }
5858         return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
5859                 new MatcherIterator(), Spliterator.ORDERED | Spliterator.NONNULL), false);
5860     }
5861 }