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