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