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