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