rev 57941 : [mq]: 8235812-Unicode-linebreak-with-quantifier-does-not-match-valid-input

   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);
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);
2907                 if (p == null)
2908                     p = CharPredicates.forProperty(shortName);
2909                 if (p == null)
2910                     p = CharPredicates.forUnicodeScript(shortName);
2911             } else {
2912                 if (has(UNICODE_CHARACTER_CLASS)) {
2913                     p = CharPredicates.forPOSIXName(name);
2914                 }
2915                 if (p == null)
2916                     p = CharPredicates.forProperty(name);
2917             }
2918             if (p == null)
2919                 throw error("Unknown character property name {" + name + "}");
2920         }
2921         if (isComplement) {
2922             // it might be too expensive to detect if a complement of
2923             // CharProperty can match "certain" supplementary. So just
2924             // go with StartS.
2925             hasSupplementary = true;
2926             p = p.negate();
2927         }
2928         return p;
2929     }
2930 
2931     private CharProperty newCharProperty(CharPredicate p) {
2932         if (p == null)
2933             return null;
2934         if (p instanceof BmpCharPredicate)
2935             return new BmpCharProperty((BmpCharPredicate)p);
2936         else
2937             return new CharProperty(p);
2938     }
2939 
2940     /**
2941      * Parses and returns the name of a "named capturing group", the trailing
2942      * ">" is consumed after parsing.
2943      */
2944     private String groupname(int ch) {
2945         StringBuilder sb = new StringBuilder();
2946         if (!ASCII.isAlpha(ch))
2947             throw error("capturing group name does not start with a Latin letter");
2948         do {
2949             sb.append((char) ch);
2950         } while (ASCII.isAlnum(ch=read()));
2951         if (ch != '>')
2952             throw error("named capturing group is missing trailing '>'");
2953         return sb.toString();
2954     }
2955 
2956     /**
2957      * Parses a group and returns the head node of a set of nodes that process
2958      * the group. Sometimes a double return system is used where the tail is
2959      * returned in root.
2960      */
2961     private Node group0() {
2962         boolean capturingGroup = false;
2963         Node head;
2964         Node tail;
2965         int save = flags0;
2966         int saveTCNCount = topClosureNodes.size();
2967         root = null;
2968         int ch = next();
2969         if (ch == '?') {
2970             ch = skip();
2971             switch (ch) {
2972             case ':':   //  (?:xxx) pure group
2973                 head = createGroup(true);
2974                 tail = root;
2975                 head.next = expr(tail);
2976                 break;
2977             case '=':   // (?=xxx) and (?!xxx) lookahead
2978             case '!':
2979                 head = createGroup(true);
2980                 tail = root;
2981                 head.next = expr(tail);
2982                 if (ch == '=') {
2983                     head = tail = new Pos(head);
2984                 } else {
2985                     head = tail = new Neg(head);
2986                 }
2987                 break;
2988             case '>':   // (?>xxx)  independent group
2989                 head = createGroup(true);
2990                 tail = root;
2991                 head.next = expr(tail);
2992                 head = tail = new Ques(head, Qtype.INDEPENDENT);
2993                 break;
2994             case '<':   // (?<xxx)  look behind
2995                 ch = read();
2996                 if (ch != '=' && ch != '!') {
2997                     // named captured group
2998                     String name = groupname(ch);
2999                     if (namedGroups().containsKey(name))
3000                         throw error("Named capturing group <" + name
3001                                     + "> is already defined");
3002                     capturingGroup = true;
3003                     head = createGroup(false);
3004                     tail = root;
3005                     namedGroups().put(name, capturingGroupCount-1);
3006                     head.next = expr(tail);
3007                     break;
3008                 }
3009                 int start = cursor;
3010                 head = createGroup(true);
3011                 tail = root;
3012                 head.next = expr(tail);
3013                 tail.next = LookBehindEndNode.INSTANCE;
3014                 TreeInfo info = new TreeInfo();
3015                 head.study(info);
3016                 if (info.maxValid == false) {
3017                     throw error("Look-behind group does not have "
3018                                 + "an obvious maximum length");
3019                 }
3020                 boolean hasSupplementary = findSupplementary(start, patternLength);
3021                 if (ch == '=') {
3022                     head = tail = (hasSupplementary ?
3023                                    new BehindS(head, info.maxLength,
3024                                                info.minLength) :
3025                                    new Behind(head, info.maxLength,
3026                                               info.minLength));
3027                 } else { // if (ch == '!')
3028                     head = tail = (hasSupplementary ?
3029                                    new NotBehindS(head, info.maxLength,
3030                                                   info.minLength) :
3031                                    new NotBehind(head, info.maxLength,
3032                                                  info.minLength));
3033                 }
3034                 // clear all top-closure-nodes inside lookbehind
3035                 if (saveTCNCount < topClosureNodes.size())
3036                     topClosureNodes.subList(saveTCNCount, topClosureNodes.size()).clear();
3037                 break;
3038             case '$':
3039             case '@':
3040                 throw error("Unknown group type");
3041             default:    // (?xxx:) inlined match flags
3042                 unread();
3043                 addFlag();
3044                 ch = read();
3045                 if (ch == ')') {
3046                     return null;    // Inline modifier only
3047                 }
3048                 if (ch != ':') {
3049                     throw error("Unknown inline modifier");
3050                 }
3051                 head = createGroup(true);
3052                 tail = root;
3053                 head.next = expr(tail);
3054                 break;
3055             }
3056         } else { // (xxx) a regular group
3057             capturingGroup = true;
3058             head = createGroup(false);
3059             tail = root;
3060             head.next = expr(tail);
3061         }
3062 
3063         accept(')', "Unclosed group");
3064         flags0 = save;
3065 
3066         // Check for quantifiers
3067         Node node = closure(head);
3068         if (node == head) { // No closure
3069             root = tail;
3070             return node;    // Dual return
3071         }
3072         if (head == tail) { // Zero length assertion
3073             root = node;
3074             return node;    // Dual return
3075         }
3076 
3077         // have group closure, clear all inner closure nodes from the
3078         // top list (no backtracking stopper optimization for inner
3079         if (saveTCNCount < topClosureNodes.size())
3080             topClosureNodes.subList(saveTCNCount, topClosureNodes.size()).clear();
3081 













3082         if (node instanceof Ques) {
3083             Ques ques = (Ques) node;
3084             if (ques.type == Qtype.POSSESSIVE) {
3085                 root = node;
3086                 return node;
3087             }
3088             tail.next = new BranchConn();
3089             tail = tail.next;
3090             if (ques.type == Qtype.GREEDY) {
3091                 head = new Branch(head, null, tail);
3092             } else { // Reluctant quantifier
3093                 head = new Branch(null, head, tail);
3094             }
3095             root = tail;
3096             return head;
3097         } else if (node instanceof Curly) {
3098             Curly curly = (Curly) node;
3099             if (curly.type == Qtype.POSSESSIVE) {
3100                 root = node;
3101                 return node;
3102             }
3103             // Discover if the group is deterministic
3104             TreeInfo info = new TreeInfo();
3105             if (head.study(info)) { // Deterministic
3106                 GroupTail temp = (GroupTail) tail;
3107                 head = root = new GroupCurly(head.next, curly.cmin,
3108                                    curly.cmax, curly.type,
3109                                    ((GroupTail)tail).localIndex,
3110                                    ((GroupTail)tail).groupIndex,
3111                                              capturingGroup);
3112                 return head;
3113             } else { // Non-deterministic
3114                 int temp = ((GroupHead) head).localIndex;
3115                 Loop loop;
3116                 if (curly.type == Qtype.GREEDY) {
3117                     loop = new Loop(this.localCount, temp);
3118                     // add the max_reps greedy to the top-closure-node list
3119                     if (curly.cmax == MAX_REPS)
3120                         topClosureNodes.add(loop);
3121                 } else {  // Reluctant Curly
3122                     loop = new LazyLoop(this.localCount, temp);
3123                 }
3124                 Prolog prolog = new Prolog(loop);
3125                 this.localCount += 1;
3126                 loop.cmin = curly.cmin;
3127                 loop.cmax = curly.cmax;
3128                 loop.body = head;
3129                 tail.next = loop;
3130                 root = loop;
3131                 return prolog; // Dual return
3132             }
3133         }
3134         throw error("Internal logic error");
3135     }
3136 
3137     /**
3138      * Create group head and tail nodes using double return. If the group is
3139      * created with anonymous true then it is a pure group and should not
3140      * affect group counting.
3141      */
3142     private Node createGroup(boolean anonymous) {
3143         int localIndex = localCount++;
3144         int groupIndex = 0;
3145         if (!anonymous)
3146             groupIndex = capturingGroupCount++;
3147         GroupHead head = new GroupHead(localIndex);
3148         root = new GroupTail(localIndex, groupIndex);
3149 
3150         // for debug/print only, head.match does NOT need the "tail" info
3151         head.tail = (GroupTail)root;
3152 
3153         if (!anonymous && groupIndex < 10)
3154             groupNodes[groupIndex] = head;
3155         return head;
3156     }
3157 
3158     @SuppressWarnings("fallthrough")
3159     /**
3160      * Parses inlined match flags and set them appropriately.
3161      */
3162     private void addFlag() {
3163         int ch = peek();
3164         for (;;) {
3165             switch (ch) {
3166             case 'i':
3167                 flags0 |= CASE_INSENSITIVE;
3168                 break;
3169             case 'm':
3170                 flags0 |= MULTILINE;
3171                 break;
3172             case 's':
3173                 flags0 |= DOTALL;
3174                 break;
3175             case 'd':
3176                 flags0 |= UNIX_LINES;
3177                 break;
3178             case 'u':
3179                 flags0 |= UNICODE_CASE;
3180                 break;
3181             case 'c':
3182                 flags0 |= CANON_EQ;
3183                 break;
3184             case 'x':
3185                 flags0 |= COMMENTS;
3186                 break;
3187             case 'U':
3188                 flags0 |= (UNICODE_CHARACTER_CLASS | UNICODE_CASE);
3189                 break;
3190             case '-': // subFlag then fall through
3191                 ch = next();
3192                 subFlag();
3193             default:
3194                 return;
3195             }
3196             ch = next();
3197         }
3198     }
3199 
3200     @SuppressWarnings("fallthrough")
3201     /**
3202      * Parses the second part of inlined match flags and turns off
3203      * flags appropriately.
3204      */
3205     private void subFlag() {
3206         int ch = peek();
3207         for (;;) {
3208             switch (ch) {
3209             case 'i':
3210                 flags0 &= ~CASE_INSENSITIVE;
3211                 break;
3212             case 'm':
3213                 flags0 &= ~MULTILINE;
3214                 break;
3215             case 's':
3216                 flags0 &= ~DOTALL;
3217                 break;
3218             case 'd':
3219                 flags0 &= ~UNIX_LINES;
3220                 break;
3221             case 'u':
3222                 flags0 &= ~UNICODE_CASE;
3223                 break;
3224             case 'c':
3225                 flags0 &= ~CANON_EQ;
3226                 break;
3227             case 'x':
3228                 flags0 &= ~COMMENTS;
3229                 break;
3230             case 'U':
3231                 flags0 &= ~(UNICODE_CHARACTER_CLASS | UNICODE_CASE);
3232                 break;
3233             default:
3234                 return;
3235             }
3236             ch = next();
3237         }
3238     }
3239 
3240     static final int MAX_REPS   = 0x7FFFFFFF;
3241 
3242     static enum Qtype {
3243         GREEDY, LAZY, POSSESSIVE, INDEPENDENT
3244     }
3245 
3246     private Qtype qtype() {
3247         int ch = next();
3248         if (ch == '?') {
3249             next();
3250             return Qtype.LAZY;
3251         } else if (ch == '+') {
3252             next();
3253             return Qtype.POSSESSIVE;
3254         }
3255         return Qtype.GREEDY;
3256     }
3257 
3258     private Node curly(Node prev, int cmin) {
3259         Qtype qtype = qtype();
3260         if (qtype == Qtype.GREEDY) {
3261             if (prev instanceof BmpCharProperty) {
3262                 return new BmpCharPropertyGreedy((BmpCharProperty)prev, cmin);
3263             } else if (prev instanceof CharProperty) {
3264                 return new CharPropertyGreedy((CharProperty)prev, cmin);
3265             }
3266         }
3267         return new Curly(prev, cmin, MAX_REPS, qtype);
3268     }
3269 
3270     /**

























3271      * Processes repetition. If the next character peeked is a quantifier
3272      * then new nodes must be appended to handle the repetition.
3273      * Prev could be a single or a group, so it could be a chain of nodes.
3274      */
3275     private Node closure(Node prev) {
3276         int ch = peek();
3277         switch (ch) {
3278         case '?':
3279             return new Ques(prev, qtype());
3280         case '*':
3281             return curly(prev, 0);
3282         case '+':
3283             return curly(prev, 1);
3284         case '{':
3285             ch = skip();
3286             if (ASCII.isDigit(ch)) {
3287                 int cmin = 0, cmax;
3288                 try {
3289                     do {
3290                         cmin = Math.addExact(Math.multiplyExact(cmin, 10),
3291                                              ch - '0');
3292                     } while (ASCII.isDigit(ch = read()));
3293                     if (ch == ',') {
3294                         ch = read();
3295                         if (ch == '}') {
3296                             unread();
3297                             return curly(prev, cmin);
3298                         } else {
3299                             cmax = 0;
3300                             while (ASCII.isDigit(ch)) {
3301                                 cmax = Math.addExact(Math.multiplyExact(cmax, 10),
3302                                                      ch - '0');
3303                                 ch = read();
3304                             }
3305                         }
3306                     } else {
3307                         cmax = cmin;
3308                     }
3309                 } catch (ArithmeticException ae) {
3310                     throw error("Illegal repetition range");
3311                 }
3312                 if (ch != '}')
3313                     throw error("Unclosed counted closure");
3314                 if (cmax < cmin)
3315                     throw error("Illegal repetition range");
3316                 unread();
3317                 return (cmin == 0 && cmax == 1)
3318                         ? new Ques(prev, qtype())
3319                         : new Curly(prev, cmin, cmax, qtype());
3320             } else {
3321                 throw error("Illegal repetition");
3322             }
3323         default:
3324             return prev;
3325         }
3326     }
3327 
3328     /**
3329      *  Utility method for parsing control escape sequences.
3330      */
3331     private int c() {
3332         if (cursor < patternLength) {
3333             return read() ^ 64;
3334         }
3335         throw error("Illegal control escape sequence");
3336     }
3337 
3338     /**
3339      *  Utility method for parsing octal escape sequences.
3340      */
3341     private int o() {
3342         int n = read();
3343         if (((n-'0')|('7'-n)) >= 0) {
3344             int m = read();
3345             if (((m-'0')|('7'-m)) >= 0) {
3346                 int o = read();
3347                 if ((((o-'0')|('7'-o)) >= 0) && (((n-'0')|('3'-n)) >= 0)) {
3348                     return (n - '0') * 64 + (m - '0') * 8 + (o - '0');
3349                 }
3350                 unread();
3351                 return (n - '0') * 8 + (m - '0');
3352             }
3353             unread();
3354             return (n - '0');
3355         }
3356         throw error("Illegal octal escape sequence");
3357     }
3358 
3359     /**
3360      *  Utility method for parsing hexadecimal escape sequences.
3361      */
3362     private int x() {
3363         int n = read();
3364         if (ASCII.isHexDigit(n)) {
3365             int m = read();
3366             if (ASCII.isHexDigit(m)) {
3367                 return ASCII.toDigit(n) * 16 + ASCII.toDigit(m);
3368             }
3369         } else if (n == '{' && ASCII.isHexDigit(peek())) {
3370             int ch = 0;
3371             while (ASCII.isHexDigit(n = read())) {
3372                 ch = (ch << 4) + ASCII.toDigit(n);
3373                 if (ch > Character.MAX_CODE_POINT)
3374                     throw error("Hexadecimal codepoint is too big");
3375             }
3376             if (n != '}')
3377                 throw error("Unclosed hexadecimal escape sequence");
3378             return ch;
3379         }
3380         throw error("Illegal hexadecimal escape sequence");
3381     }
3382 
3383     /**
3384      *  Utility method for parsing unicode escape sequences.
3385      */
3386     private int cursor() {
3387         return cursor;
3388     }
3389 
3390     private void setcursor(int pos) {
3391         cursor = pos;
3392     }
3393 
3394     private int uxxxx() {
3395         int n = 0;
3396         for (int i = 0; i < 4; i++) {
3397             int ch = read();
3398             if (!ASCII.isHexDigit(ch)) {
3399                 throw error("Illegal Unicode escape sequence");
3400             }
3401             n = n * 16 + ASCII.toDigit(ch);
3402         }
3403         return n;
3404     }
3405 
3406     private int u() {
3407         int n = uxxxx();
3408         if (Character.isHighSurrogate((char)n)) {
3409             int cur = cursor();
3410             if (read() == '\\' && read() == 'u') {
3411                 int n2 = uxxxx();
3412                 if (Character.isLowSurrogate((char)n2))
3413                     return Character.toCodePoint((char)n, (char)n2);
3414             }
3415             setcursor(cur);
3416         }
3417         return n;
3418     }
3419 
3420     private int N() {
3421         if (read() == '{') {
3422             int i = cursor;
3423             while (read() != '}') {
3424                 if (cursor >= patternLength)
3425                     throw error("Unclosed character name escape sequence");
3426             }
3427             String name = new String(temp, i, cursor - i - 1);
3428             try {
3429                 return Character.codePointOf(name);
3430             } catch (IllegalArgumentException x) {
3431                 throw error("Unknown character name [" + name + "]");
3432             }
3433         }
3434         throw error("Illegal character name escape sequence");
3435     }
3436 
3437     //
3438     // Utility methods for code point support
3439     //
3440     private static final int countChars(CharSequence seq, int index,
3441                                         int lengthInCodePoints) {
3442         // optimization
3443         if (lengthInCodePoints == 1 && !Character.isHighSurrogate(seq.charAt(index))) {
3444             assert (index >= 0 && index < seq.length());
3445             return 1;
3446         }
3447         int length = seq.length();
3448         int x = index;
3449         if (lengthInCodePoints >= 0) {
3450             assert (index >= 0 && index < length);
3451             for (int i = 0; x < length && i < lengthInCodePoints; i++) {
3452                 if (Character.isHighSurrogate(seq.charAt(x++))) {
3453                     if (x < length && Character.isLowSurrogate(seq.charAt(x))) {
3454                         x++;
3455                     }
3456                 }
3457             }
3458             return x - index;
3459         }
3460 
3461         assert (index >= 0 && index <= length);
3462         if (index == 0) {
3463             return 0;
3464         }
3465         int len = -lengthInCodePoints;
3466         for (int i = 0; x > 0 && i < len; i++) {
3467             if (Character.isLowSurrogate(seq.charAt(--x))) {
3468                 if (x > 0 && Character.isHighSurrogate(seq.charAt(x-1))) {
3469                     x--;
3470                 }
3471             }
3472         }
3473         return index - x;
3474     }
3475 
3476     private static final int countCodePoints(CharSequence seq) {
3477         int length = seq.length();
3478         int n = 0;
3479         for (int i = 0; i < length; ) {
3480             n++;
3481             if (Character.isHighSurrogate(seq.charAt(i++))) {
3482                 if (i < length && Character.isLowSurrogate(seq.charAt(i))) {
3483                     i++;
3484                 }
3485             }
3486         }
3487         return n;
3488     }
3489 
3490     /**
3491      *  Creates a bit vector for matching Latin-1 values. A normal BitClass
3492      *  never matches values above Latin-1, and a complemented BitClass always
3493      *  matches values above Latin-1.
3494      */
3495     static final class BitClass implements BmpCharPredicate {
3496         final boolean[] bits;
3497         BitClass() {
3498             bits = new boolean[256];
3499         }
3500         BitClass add(int c, int flags) {
3501             assert c >= 0 && c <= 255;
3502             if ((flags & CASE_INSENSITIVE) != 0) {
3503                 if (ASCII.isAscii(c)) {
3504                     bits[ASCII.toUpper(c)] = true;
3505                     bits[ASCII.toLower(c)] = true;
3506                 } else if ((flags & UNICODE_CASE) != 0) {
3507                     bits[Character.toLowerCase(c)] = true;
3508                     bits[Character.toUpperCase(c)] = true;
3509                 }
3510             }
3511             bits[c] = true;
3512             return this;
3513         }
3514         public boolean is(int ch) {
3515             return ch < 256 && bits[ch];
3516         }
3517     }
3518 
3519 
3520     /**
3521      *  Utility method for creating a string slice matcher.
3522      */
3523     private Node newSlice(int[] buf, int count, boolean hasSupplementary) {
3524         int[] tmp = new int[count];
3525         if (has(CASE_INSENSITIVE)) {
3526             if (has(UNICODE_CASE)) {
3527                 for (int i = 0; i < count; i++) {
3528                     tmp[i] = Character.toLowerCase(
3529                                  Character.toUpperCase(buf[i]));
3530                 }
3531                 return hasSupplementary? new SliceUS(tmp) : new SliceU(tmp);
3532             }
3533             for (int i = 0; i < count; i++) {
3534                 tmp[i] = ASCII.toLower(buf[i]);
3535             }
3536             return hasSupplementary? new SliceIS(tmp) : new SliceI(tmp);
3537         }
3538         for (int i = 0; i < count; i++) {
3539             tmp[i] = buf[i];
3540         }
3541         return hasSupplementary ? new SliceS(tmp) : new Slice(tmp);
3542     }
3543 
3544     /**
3545      * The following classes are the building components of the object
3546      * tree that represents a compiled regular expression. The object tree
3547      * is made of individual elements that handle constructs in the Pattern.
3548      * Each type of object knows how to match its equivalent construct with
3549      * the match() method.
3550      */
3551 
3552     /**
3553      * Base class for all node classes. Subclasses should override the match()
3554      * method as appropriate. This class is an accepting node, so its match()
3555      * always returns true.
3556      */
3557     static class Node extends Object {
3558         Node next;
3559         Node() {
3560             next = Pattern.accept;
3561         }
3562         /**
3563          * This method implements the classic accept node.
3564          */
3565         boolean match(Matcher matcher, int i, CharSequence seq) {
3566             matcher.last = i;
3567             matcher.groups[0] = matcher.first;
3568             matcher.groups[1] = matcher.last;
3569             return true;
3570         }
3571         /**
3572          * This method is good for all zero length assertions.
3573          */
3574         boolean study(TreeInfo info) {
3575             if (next != null) {
3576                 return next.study(info);
3577             } else {
3578                 return info.deterministic;
3579             }
3580         }
3581     }
3582 
3583     static class LastNode extends Node {
3584         /**
3585          * This method implements the classic accept node with
3586          * the addition of a check to see if the match occurred
3587          * using all of the input.
3588          */
3589         boolean match(Matcher matcher, int i, CharSequence seq) {
3590             if (matcher.acceptMode == Matcher.ENDANCHOR && i != matcher.to)
3591                 return false;
3592             matcher.last = i;
3593             matcher.groups[0] = matcher.first;
3594             matcher.groups[1] = matcher.last;
3595             return true;
3596         }
3597     }
3598 
3599     /**
3600      * Used for REs that can start anywhere within the input string.
3601      * This basically tries to match repeatedly at each spot in the
3602      * input string, moving forward after each try. An anchored search
3603      * or a BnM will bypass this node completely.
3604      */
3605     static class Start extends Node {
3606         int minLength;
3607         Start(Node node) {
3608             this.next = node;
3609             TreeInfo info = new TreeInfo();
3610             next.study(info);
3611             minLength = info.minLength;
3612         }
3613         boolean match(Matcher matcher, int i, CharSequence seq) {
3614             if (i > matcher.to - minLength) {
3615                 matcher.hitEnd = true;
3616                 return false;
3617             }
3618             int guard = matcher.to - minLength;
3619             for (; i <= guard; i++) {
3620                 if (next.match(matcher, i, seq)) {
3621                     matcher.first = i;
3622                     matcher.groups[0] = matcher.first;
3623                     matcher.groups[1] = matcher.last;
3624                     return true;
3625                 }
3626             }
3627             matcher.hitEnd = true;
3628             return false;
3629         }
3630         boolean study(TreeInfo info) {
3631             next.study(info);
3632             info.maxValid = false;
3633             info.deterministic = false;
3634             return false;
3635         }
3636     }
3637 
3638     /*
3639      * StartS supports supplementary characters, including unpaired surrogates.
3640      */
3641     static final class StartS extends Start {
3642         StartS(Node node) {
3643             super(node);
3644         }
3645         boolean match(Matcher matcher, int i, CharSequence seq) {
3646             if (i > matcher.to - minLength) {
3647                 matcher.hitEnd = true;
3648                 return false;
3649             }
3650             int guard = matcher.to - minLength;
3651             while (i <= guard) {
3652                 //if ((ret = next.match(matcher, i, seq)) || i == guard)
3653                 if (next.match(matcher, i, seq)) {
3654                     matcher.first = i;
3655                     matcher.groups[0] = matcher.first;
3656                     matcher.groups[1] = matcher.last;
3657                     return true;
3658                 }
3659                 if (i == guard)
3660                     break;
3661                 // Optimization to move to the next character. This is
3662                 // faster than countChars(seq, i, 1).
3663                 if (Character.isHighSurrogate(seq.charAt(i++))) {
3664                     if (i < seq.length() &&
3665                         Character.isLowSurrogate(seq.charAt(i))) {
3666                         i++;
3667                     }
3668                 }
3669             }
3670             matcher.hitEnd = true;
3671             return false;
3672         }
3673     }
3674 
3675     /**
3676      * Node to anchor at the beginning of input. This object implements the
3677      * match for a \A sequence, and the caret anchor will use this if not in
3678      * multiline mode.
3679      */
3680     static final class Begin extends Node {
3681         boolean match(Matcher matcher, int i, CharSequence seq) {
3682             int fromIndex = (matcher.anchoringBounds) ?
3683                 matcher.from : 0;
3684             if (i == fromIndex && next.match(matcher, i, seq)) {
3685                 matcher.first = i;
3686                 matcher.groups[0] = i;
3687                 matcher.groups[1] = matcher.last;
3688                 return true;
3689             } else {
3690                 return false;
3691             }
3692         }
3693     }
3694 
3695     /**
3696      * Node to anchor at the end of input. This is the absolute end, so this
3697      * should not match at the last newline before the end as $ will.
3698      */
3699     static final class End extends Node {
3700         boolean match(Matcher matcher, int i, CharSequence seq) {
3701             int endIndex = (matcher.anchoringBounds) ?
3702                 matcher.to : matcher.getTextLength();
3703             if (i == endIndex) {
3704                 matcher.hitEnd = true;
3705                 return next.match(matcher, i, seq);
3706             }
3707             return false;
3708         }
3709     }
3710 
3711     /**
3712      * Node to anchor at the beginning of a line. This is essentially the
3713      * object to match for the multiline ^.
3714      */
3715     static final class Caret extends Node {
3716         boolean match(Matcher matcher, int i, CharSequence seq) {
3717             int startIndex = matcher.from;
3718             int endIndex = matcher.to;
3719             if (!matcher.anchoringBounds) {
3720                 startIndex = 0;
3721                 endIndex = matcher.getTextLength();
3722             }
3723             // Perl does not match ^ at end of input even after newline
3724             if (i == endIndex) {
3725                 matcher.hitEnd = true;
3726                 return false;
3727             }
3728             if (i > startIndex) {
3729                 char ch = seq.charAt(i-1);
3730                 if (ch != '\n' && ch != '\r'
3731                     && (ch|1) != '\u2029'
3732                     && ch != '\u0085' ) {
3733                     return false;
3734                 }
3735                 // Should treat /r/n as one newline
3736                 if (ch == '\r' && seq.charAt(i) == '\n')
3737                     return false;
3738             }
3739             return next.match(matcher, i, seq);
3740         }
3741     }
3742 
3743     /**
3744      * Node to anchor at the beginning of a line when in unixdot mode.
3745      */
3746     static final class UnixCaret extends Node {
3747         boolean match(Matcher matcher, int i, CharSequence seq) {
3748             int startIndex = matcher.from;
3749             int endIndex = matcher.to;
3750             if (!matcher.anchoringBounds) {
3751                 startIndex = 0;
3752                 endIndex = matcher.getTextLength();
3753             }
3754             // Perl does not match ^ at end of input even after newline
3755             if (i == endIndex) {
3756                 matcher.hitEnd = true;
3757                 return false;
3758             }
3759             if (i > startIndex) {
3760                 char ch = seq.charAt(i-1);
3761                 if (ch != '\n') {
3762                     return false;
3763                 }
3764             }
3765             return next.match(matcher, i, seq);
3766         }
3767     }
3768 
3769     /**
3770      * Node to match the location where the last match ended.
3771      * This is used for the \G construct.
3772      */
3773     static final class LastMatch extends Node {
3774         boolean match(Matcher matcher, int i, CharSequence seq) {
3775             if (i != matcher.oldLast)
3776                 return false;
3777             return next.match(matcher, i, seq);
3778         }
3779     }
3780 
3781     /**
3782      * Node to anchor at the end of a line or the end of input based on the
3783      * multiline mode.
3784      *
3785      * When not in multiline mode, the $ can only match at the very end
3786      * of the input, unless the input ends in a line terminator in which
3787      * it matches right before the last line terminator.
3788      *
3789      * Note that \r\n is considered an atomic line terminator.
3790      *
3791      * Like ^ the $ operator matches at a position, it does not match the
3792      * line terminators themselves.
3793      */
3794     static final class Dollar extends Node {
3795         boolean multiline;
3796         Dollar(boolean mul) {
3797             multiline = mul;
3798         }
3799         boolean match(Matcher matcher, int i, CharSequence seq) {
3800             int endIndex = (matcher.anchoringBounds) ?
3801                 matcher.to : matcher.getTextLength();
3802             if (!multiline) {
3803                 if (i < endIndex - 2)
3804                     return false;
3805                 if (i == endIndex - 2) {
3806                     char ch = seq.charAt(i);
3807                     if (ch != '\r')
3808                         return false;
3809                     ch = seq.charAt(i + 1);
3810                     if (ch != '\n')
3811                         return false;
3812                 }
3813             }
3814             // Matches before any line terminator; also matches at the
3815             // end of input
3816             // Before line terminator:
3817             // If multiline, we match here no matter what
3818             // If not multiline, fall through so that the end
3819             // is marked as hit; this must be a /r/n or a /n
3820             // at the very end so the end was hit; more input
3821             // could make this not match here
3822             if (i < endIndex) {
3823                 char ch = seq.charAt(i);
3824                  if (ch == '\n') {
3825                      // No match between \r\n
3826                      if (i > 0 && seq.charAt(i-1) == '\r')
3827                          return false;
3828                      if (multiline)
3829                          return next.match(matcher, i, seq);
3830                  } else if (ch == '\r' || ch == '\u0085' ||
3831                             (ch|1) == '\u2029') {
3832                      if (multiline)
3833                          return next.match(matcher, i, seq);
3834                  } else { // No line terminator, no match
3835                      return false;
3836                  }
3837             }
3838             // Matched at current end so hit end
3839             matcher.hitEnd = true;
3840             // If a $ matches because of end of input, then more input
3841             // could cause it to fail!
3842             matcher.requireEnd = true;
3843             return next.match(matcher, i, seq);
3844         }
3845         boolean study(TreeInfo info) {
3846             next.study(info);
3847             return info.deterministic;
3848         }
3849     }
3850 
3851     /**
3852      * Node to anchor at the end of a line or the end of input based on the
3853      * multiline mode when in unix lines mode.
3854      */
3855     static final class UnixDollar extends Node {
3856         boolean multiline;
3857         UnixDollar(boolean mul) {
3858             multiline = mul;
3859         }
3860         boolean match(Matcher matcher, int i, CharSequence seq) {
3861             int endIndex = (matcher.anchoringBounds) ?
3862                 matcher.to : matcher.getTextLength();
3863             if (i < endIndex) {
3864                 char ch = seq.charAt(i);
3865                 if (ch == '\n') {
3866                     // If not multiline, then only possible to
3867                     // match at very end or one before end
3868                     if (multiline == false && i != endIndex - 1)
3869                         return false;
3870                     // If multiline return next.match without setting
3871                     // matcher.hitEnd
3872                     if (multiline)
3873                         return next.match(matcher, i, seq);
3874                 } else {
3875                     return false;
3876                 }
3877             }
3878             // Matching because at the end or 1 before the end;
3879             // more input could change this so set hitEnd
3880             matcher.hitEnd = true;
3881             // If a $ matches because of end of input, then more input
3882             // could cause it to fail!
3883             matcher.requireEnd = true;
3884             return next.match(matcher, i, seq);
3885         }
3886         boolean study(TreeInfo info) {
3887             next.study(info);
3888             return info.deterministic;
3889         }
3890     }
3891 
3892     /**
3893      * Node class that matches a Unicode line ending '\R'
3894      */
3895     static final class LineEnding extends Node {
3896         boolean match(Matcher matcher, int i, CharSequence seq) {
3897             // (u+000Du+000A|[u+000Au+000Bu+000Cu+000Du+0085u+2028u+2029])
3898             if (i < matcher.to) {
3899                 int ch = seq.charAt(i);
3900                 if (ch == 0x0A || ch == 0x0B || ch == 0x0C ||
3901                     ch == 0x85 || ch == 0x2028 || ch == 0x2029)
3902                     return next.match(matcher, i + 1, seq);
3903                 if (ch == 0x0D) {
3904                     i++;
3905                     if (i < matcher.to) {
3906                         if (seq.charAt(i) == 0x0A &&
3907                             next.match(matcher, i + 1, seq)) {
3908                             return true;
3909                         }
3910                     } else {
3911                         matcher.hitEnd = true;
3912                     }
3913                     return next.match(matcher, i, seq);
3914                 }
3915             } else {
3916                 matcher.hitEnd = true;
3917             }
3918             return false;
3919         }
3920         boolean study(TreeInfo info) {
3921             info.minLength++;
3922             info.maxLength += 2;
3923             return next.study(info);
3924         }
3925     }
3926 
3927     /**
3928      * Abstract node class to match one character satisfying some
3929      * boolean property.
3930      */
3931     static class CharProperty extends Node {
3932         final CharPredicate predicate;
3933 
3934         CharProperty (CharPredicate predicate) {
3935             this.predicate = predicate;
3936         }
3937         boolean match(Matcher matcher, int i, CharSequence seq) {
3938             if (i < matcher.to) {
3939                 int ch = Character.codePointAt(seq, i);
3940                 i += Character.charCount(ch);
3941                 if (i <= matcher.to) {
3942                     return predicate.is(ch) &&
3943                            next.match(matcher, i, seq);
3944                 }
3945             }
3946             matcher.hitEnd = true;
3947             return false;
3948         }
3949         boolean study(TreeInfo info) {
3950             info.minLength++;
3951             info.maxLength++;
3952             return next.study(info);
3953         }
3954     }
3955 
3956     /**
3957      * Optimized version of CharProperty that works only for
3958      * properties never satisfied by Supplementary characters.
3959      */
3960     private static class BmpCharProperty extends CharProperty {
3961         BmpCharProperty (BmpCharPredicate predicate) {
3962             super(predicate);
3963         }
3964         boolean match(Matcher matcher, int i, CharSequence seq) {
3965             if (i < matcher.to) {
3966                 return predicate.is(seq.charAt(i)) &&
3967                        next.match(matcher, i + 1, seq);
3968             } else {
3969                 matcher.hitEnd = true;
3970                 return false;
3971             }
3972         }
3973     }
3974 
3975     private static class NFCCharProperty extends Node {
3976         CharPredicate predicate;
3977         NFCCharProperty (CharPredicate predicate) {
3978             this.predicate = predicate;
3979         }
3980 
3981         boolean match(Matcher matcher, int i, CharSequence seq) {
3982             if (i < matcher.to) {
3983                 int ch0 = Character.codePointAt(seq, i);
3984                 int n = Character.charCount(ch0);
3985                 int j = i + n;
3986                 // Fast check if it's necessary to call Normalizer;
3987                 // testing Grapheme.isBoundary is enough for this case
3988                 while (j < matcher.to) {
3989                     int ch1 = Character.codePointAt(seq, j);
3990                     if (Grapheme.isBoundary(ch0, ch1))
3991                         break;
3992                     ch0 = ch1;
3993                     j += Character.charCount(ch1);
3994                 }
3995                 if (i + n == j) {    // single, assume nfc cp
3996                     if (predicate.is(ch0))
3997                         return next.match(matcher, j, seq);
3998                 } else {
3999                     while (i + n < j) {
4000                         String nfc = Normalizer.normalize(
4001                             seq.toString().substring(i, j), Normalizer.Form.NFC);
4002                         if (nfc.codePointCount(0, nfc.length()) == 1) {
4003                             if (predicate.is(nfc.codePointAt(0)) &&
4004                                 next.match(matcher, j, seq)) {
4005                                 return true;
4006                             }
4007                         }
4008 
4009                         ch0 = Character.codePointBefore(seq, j);
4010                         j -= Character.charCount(ch0);
4011                     }
4012                 }
4013                 if (j < matcher.to)
4014                     return false;
4015             }
4016             matcher.hitEnd = true;
4017             return false;
4018         }
4019 
4020         boolean study(TreeInfo info) {
4021             info.minLength++;
4022             info.deterministic = false;
4023             return next.study(info);
4024         }
4025     }
4026 
4027     /**
4028      * Node class that matches an unicode extended grapheme cluster
4029      */
4030     static class XGrapheme extends Node {
4031         boolean match(Matcher matcher, int i, CharSequence seq) {
4032             if (i < matcher.to) {
4033                 i = Grapheme.nextBoundary(seq, i, matcher.to);
4034                 return next.match(matcher, i, seq);
4035             }
4036             matcher.hitEnd = true;
4037             return false;
4038         }
4039 
4040         boolean study(TreeInfo info) {
4041             info.minLength++;
4042             info.deterministic = false;
4043             return next.study(info);
4044         }
4045     }
4046 
4047     /**
4048      * Node class that handles grapheme boundaries
4049      */
4050     static class GraphemeBound extends Node {
4051         boolean match(Matcher matcher, int i, CharSequence seq) {
4052             int startIndex = matcher.from;
4053             int endIndex = matcher.to;
4054             if (matcher.transparentBounds) {
4055                 startIndex = 0;
4056                 endIndex = matcher.getTextLength();
4057             }
4058             if (i == startIndex) {
4059                 return next.match(matcher, i, seq);
4060             }
4061             if (i < endIndex) {
4062                 if (Character.isSurrogatePair(seq.charAt(i-1), seq.charAt(i)) ||
4063                     Grapheme.nextBoundary(seq,
4064                         i - Character.charCount(Character.codePointBefore(seq, i)),
4065                         i + Character.charCount(Character.codePointAt(seq, i))) > i) {
4066                     return false;
4067                 }
4068             } else {
4069                 matcher.hitEnd = true;
4070                 matcher.requireEnd = true;
4071             }
4072             return next.match(matcher, i, seq);
4073         }
4074     }
4075 
4076     /**
4077      * Base class for all Slice nodes
4078      */
4079     static class SliceNode extends Node {
4080         int[] buffer;
4081         SliceNode(int[] buf) {
4082             buffer = buf;
4083         }
4084         boolean study(TreeInfo info) {
4085             info.minLength += buffer.length;
4086             info.maxLength += buffer.length;
4087             return next.study(info);
4088         }
4089     }
4090 
4091     /**
4092      * Node class for a case sensitive/BMP-only sequence of literal
4093      * characters.
4094      */
4095     static class Slice extends SliceNode {
4096         Slice(int[] buf) {
4097             super(buf);
4098         }
4099         boolean match(Matcher matcher, int i, CharSequence seq) {
4100             int[] buf = buffer;
4101             int len = buf.length;
4102             for (int j=0; j<len; j++) {
4103                 if ((i+j) >= matcher.to) {
4104                     matcher.hitEnd = true;
4105                     return false;
4106                 }
4107                 if (buf[j] != seq.charAt(i+j))
4108                     return false;
4109             }
4110             return next.match(matcher, i+len, seq);
4111         }
4112     }
4113 
4114     /**
4115      * Node class for a case_insensitive/BMP-only sequence of literal
4116      * characters.
4117      */
4118     static class SliceI extends SliceNode {
4119         SliceI(int[] buf) {
4120             super(buf);
4121         }
4122         boolean match(Matcher matcher, int i, CharSequence seq) {
4123             int[] buf = buffer;
4124             int len = buf.length;
4125             for (int j=0; j<len; j++) {
4126                 if ((i+j) >= matcher.to) {
4127                     matcher.hitEnd = true;
4128                     return false;
4129                 }
4130                 int c = seq.charAt(i+j);
4131                 if (buf[j] != c &&
4132                     buf[j] != ASCII.toLower(c))
4133                     return false;
4134             }
4135             return next.match(matcher, i+len, seq);
4136         }
4137     }
4138 
4139     /**
4140      * Node class for a unicode_case_insensitive/BMP-only sequence of
4141      * literal characters. Uses unicode case folding.
4142      */
4143     static final class SliceU extends SliceNode {
4144         SliceU(int[] buf) {
4145             super(buf);
4146         }
4147         boolean match(Matcher matcher, int i, CharSequence seq) {
4148             int[] buf = buffer;
4149             int len = buf.length;
4150             for (int j=0; j<len; j++) {
4151                 if ((i+j) >= matcher.to) {
4152                     matcher.hitEnd = true;
4153                     return false;
4154                 }
4155                 int c = seq.charAt(i+j);
4156                 if (buf[j] != c &&
4157                     buf[j] != Character.toLowerCase(Character.toUpperCase(c)))
4158                     return false;
4159             }
4160             return next.match(matcher, i+len, seq);
4161         }
4162     }
4163 
4164     /**
4165      * Node class for a case sensitive sequence of literal characters
4166      * including supplementary characters.
4167      */
4168     static final class SliceS extends Slice {
4169         SliceS(int[] buf) {
4170             super(buf);
4171         }
4172         boolean match(Matcher matcher, int i, CharSequence seq) {
4173             int[] buf = buffer;
4174             int x = i;
4175             for (int j = 0; j < buf.length; j++) {
4176                 if (x >= matcher.to) {
4177                     matcher.hitEnd = true;
4178                     return false;
4179                 }
4180                 int c = Character.codePointAt(seq, x);
4181                 if (buf[j] != c)
4182                     return false;
4183                 x += Character.charCount(c);
4184                 if (x > matcher.to) {
4185                     matcher.hitEnd = true;
4186                     return false;
4187                 }
4188             }
4189             return next.match(matcher, x, seq);
4190         }
4191     }
4192 
4193     /**
4194      * Node class for a case insensitive sequence of literal characters
4195      * including supplementary characters.
4196      */
4197     static class SliceIS extends SliceNode {
4198         SliceIS(int[] buf) {
4199             super(buf);
4200         }
4201         int toLower(int c) {
4202             return ASCII.toLower(c);
4203         }
4204         boolean match(Matcher matcher, int i, CharSequence seq) {
4205             int[] buf = buffer;
4206             int x = i;
4207             for (int j = 0; j < buf.length; j++) {
4208                 if (x >= matcher.to) {
4209                     matcher.hitEnd = true;
4210                     return false;
4211                 }
4212                 int c = Character.codePointAt(seq, x);
4213                 if (buf[j] != c && buf[j] != toLower(c))
4214                     return false;
4215                 x += Character.charCount(c);
4216                 if (x > matcher.to) {
4217                     matcher.hitEnd = true;
4218                     return false;
4219                 }
4220             }
4221             return next.match(matcher, x, seq);
4222         }
4223     }
4224 
4225     /**
4226      * Node class for a case insensitive sequence of literal characters.
4227      * Uses unicode case folding.
4228      */
4229     static final class SliceUS extends SliceIS {
4230         SliceUS(int[] buf) {
4231             super(buf);
4232         }
4233         int toLower(int c) {
4234             return Character.toLowerCase(Character.toUpperCase(c));
4235         }
4236     }
4237 
4238     /**
4239      * The 0 or 1 quantifier. This one class implements all three types.
4240      */
4241     static final class Ques extends Node {
4242         Node atom;
4243         Qtype type;
4244         Ques(Node node, Qtype type) {
4245             this.atom = node;
4246             this.type = type;
4247         }
4248         boolean match(Matcher matcher, int i, CharSequence seq) {
4249             switch (type) {
4250             case GREEDY:
4251                 return (atom.match(matcher, i, seq) && next.match(matcher, matcher.last, seq))
4252                     || next.match(matcher, i, seq);
4253             case LAZY:
4254                 return next.match(matcher, i, seq)
4255                     || (atom.match(matcher, i, seq) && next.match(matcher, matcher.last, seq));
4256             case POSSESSIVE:
4257                 if (atom.match(matcher, i, seq)) i = matcher.last;
4258                 return next.match(matcher, i, seq);
4259             default:
4260                 return atom.match(matcher, i, seq) && next.match(matcher, matcher.last, seq);
4261             }
4262         }
4263         boolean study(TreeInfo info) {
4264             if (type != Qtype.INDEPENDENT) {
4265                 int minL = info.minLength;
4266                 atom.study(info);
4267                 info.minLength = minL;
4268                 info.deterministic = false;
4269                 return next.study(info);
4270             } else {
4271                 atom.study(info);
4272                 return next.study(info);
4273             }
4274         }
4275     }
4276 
4277     /**
4278      * Handles the greedy style repetition with the specified minimum
4279      * and the maximum equal to MAX_REPS, for *, + and {N,} quantifiers.
4280      */
4281     static class CharPropertyGreedy extends Node {
4282         final CharPredicate predicate;
4283         final int cmin;
4284 
4285         CharPropertyGreedy(CharProperty cp, int cmin) {
4286             this.predicate = cp.predicate;
4287             this.cmin = cmin;
4288         }
4289         boolean match(Matcher matcher, int i, CharSequence seq) {
4290             int n = 0;
4291             int to = matcher.to;
4292             // greedy, all the way down
4293             while (i < to) {
4294                 int ch = Character.codePointAt(seq, i);
4295                 if (!predicate.is(ch))
4296                    break;
4297                 i += Character.charCount(ch);
4298                 n++;
4299             }
4300             if (i >= to) {
4301                 matcher.hitEnd = true;
4302             }
4303             while (n >= cmin) {
4304                 if (next.match(matcher, i, seq))
4305                     return true;
4306                 if (n == cmin)
4307                     return false;
4308                  // backing off if match fails
4309                 int ch = Character.codePointBefore(seq, i);
4310                 i -= Character.charCount(ch);
4311                 n--;
4312             }
4313             return false;
4314         }
4315 
4316         boolean study(TreeInfo info) {
4317             info.minLength += cmin;
4318             if (info.maxValid) {
4319                 info.maxLength += MAX_REPS;
4320             }
4321             info.deterministic = false;
4322             return next.study(info);
4323         }
4324     }
4325 
4326     static final class BmpCharPropertyGreedy extends CharPropertyGreedy {
4327 
4328         BmpCharPropertyGreedy(BmpCharProperty bcp, int cmin) {
4329             super(bcp, cmin);
4330         }
4331 
4332         boolean match(Matcher matcher, int i, CharSequence seq) {
4333             int n = 0;
4334             int to = matcher.to;
4335             while (i < to && predicate.is(seq.charAt(i))) {
4336                 i++; n++;
4337             }
4338             if (i >= to) {
4339                 matcher.hitEnd = true;
4340             }
4341             while (n >= cmin) {
4342                 if (next.match(matcher, i, seq))
4343                     return true;
4344                 i--; n--;  // backing off if match fails
4345             }
4346             return false;
4347         }
4348     }
4349 
4350     /**
4351      * Handles the curly-brace style repetition with a specified minimum and
4352      * maximum occurrences. The * quantifier is handled as a special case.
4353      * This class handles the three types.
4354      */
4355     static final class Curly extends Node {
4356         Node atom;
4357         Qtype type;
4358         int cmin;
4359         int cmax;
4360 
4361         Curly(Node node, int cmin, int cmax, Qtype type) {
4362             this.atom = node;
4363             this.type = type;
4364             this.cmin = cmin;
4365             this.cmax = cmax;
4366         }
4367         boolean match(Matcher matcher, int i, CharSequence seq) {
4368             int j;
4369             for (j = 0; j < cmin; j++) {
4370                 if (atom.match(matcher, i, seq)) {
4371                     i = matcher.last;
4372                     continue;
4373                 }
4374                 return false;
4375             }
4376             if (type == Qtype.GREEDY)
4377                 return match0(matcher, i, j, seq);
4378             else if (type == Qtype.LAZY)
4379                 return match1(matcher, i, j, seq);
4380             else
4381                 return match2(matcher, i, j, seq);
4382         }
4383         // Greedy match.
4384         // i is the index to start matching at
4385         // j is the number of atoms that have matched
4386         boolean match0(Matcher matcher, int i, int j, CharSequence seq) {
4387             if (j >= cmax) {
4388                 // We have matched the maximum... continue with the rest of
4389                 // the regular expression
4390                 return next.match(matcher, i, seq);
4391             }
4392             int backLimit = j;
4393             while (atom.match(matcher, i, seq)) {
4394                 // k is the length of this match
4395                 int k = matcher.last - i;
4396                 if (k == 0) // Zero length match
4397                     break;
4398                 // Move up index and number matched
4399                 i = matcher.last;
4400                 j++;
4401                 // We are greedy so match as many as we can
4402                 while (j < cmax) {
4403                     if (!atom.match(matcher, i, seq))
4404                         break;
4405                     if (i + k != matcher.last) {
4406                         if (match0(matcher, matcher.last, j+1, seq))
4407                             return true;
4408                         break;
4409                     }
4410                     i += k;
4411                     j++;
4412                 }
4413                 // Handle backing off if match fails
4414                 while (j >= backLimit) {
4415                    if (next.match(matcher, i, seq))
4416                         return true;
4417                     i -= k;
4418                     j--;
4419                 }
4420                 return false;
4421             }
4422             return next.match(matcher, i, seq);
4423         }
4424         // Reluctant match. At this point, the minimum has been satisfied.
4425         // i is the index to start matching at
4426         // j is the number of atoms that have matched
4427         boolean match1(Matcher matcher, int i, int j, CharSequence seq) {
4428             for (;;) {
4429                 // Try finishing match without consuming any more
4430                 if (next.match(matcher, i, seq))
4431                     return true;
4432                 // At the maximum, no match found
4433                 if (j >= cmax)
4434                     return false;
4435                 // Okay, must try one more atom
4436                 if (!atom.match(matcher, i, seq))
4437                     return false;
4438                 // If we haven't moved forward then must break out
4439                 if (i == matcher.last)
4440                     return false;
4441                 // Move up index and number matched
4442                 i = matcher.last;
4443                 j++;
4444             }
4445         }
4446         boolean match2(Matcher matcher, int i, int j, CharSequence seq) {
4447             for (; j < cmax; j++) {
4448                 if (!atom.match(matcher, i, seq))
4449                     break;
4450                 if (i == matcher.last)
4451                     break;
4452                 i = matcher.last;
4453             }
4454             return next.match(matcher, i, seq);
4455         }
4456         boolean study(TreeInfo info) {
4457             // Save original info
4458             int minL = info.minLength;
4459             int maxL = info.maxLength;
4460             boolean maxV = info.maxValid;
4461             boolean detm = info.deterministic;
4462             info.reset();
4463 
4464             atom.study(info);
4465 
4466             int temp = info.minLength * cmin + minL;
4467             if (temp < minL) {
4468                 temp = 0xFFFFFFF; // arbitrary large number
4469             }
4470             info.minLength = temp;
4471 
4472             if (maxV & info.maxValid) {
4473                 temp = info.maxLength * cmax + maxL;
4474                 info.maxLength = temp;
4475                 if (temp < maxL) {
4476                     info.maxValid = false;
4477                 }
4478             } else {
4479                 info.maxValid = false;
4480             }
4481 
4482             if (info.deterministic && cmin == cmax)
4483                 info.deterministic = detm;
4484             else
4485                 info.deterministic = false;
4486             return next.study(info);
4487         }
4488     }
4489 
4490     /**
4491      * Handles the curly-brace style repetition with a specified minimum and
4492      * maximum occurrences in deterministic cases. This is an iterative
4493      * optimization over the Prolog and Loop system which would handle this
4494      * in a recursive way. The * quantifier is handled as a special case.
4495      * If capture is true then this class saves group settings and ensures
4496      * that groups are unset when backing off of a group match.
4497      */
4498     static final class GroupCurly extends Node {
4499         Node atom;
4500         Qtype type;
4501         int cmin;
4502         int cmax;
4503         int localIndex;
4504         int groupIndex;
4505         boolean capture;
4506 
4507         GroupCurly(Node node, int cmin, int cmax, Qtype type, int local,
4508                    int group, boolean capture) {
4509             this.atom = node;
4510             this.type = type;
4511             this.cmin = cmin;
4512             this.cmax = cmax;
4513             this.localIndex = local;
4514             this.groupIndex = group;
4515             this.capture = capture;
4516         }
4517         boolean match(Matcher matcher, int i, CharSequence seq) {
4518             int[] groups = matcher.groups;
4519             int[] locals = matcher.locals;
4520             int save0 = locals[localIndex];
4521             int save1 = 0;
4522             int save2 = 0;
4523 
4524             if (capture) {
4525                 save1 = groups[groupIndex];
4526                 save2 = groups[groupIndex+1];
4527             }
4528 
4529             // Notify GroupTail there is no need to setup group info
4530             // because it will be set here
4531             locals[localIndex] = -1;
4532 
4533             boolean ret = true;
4534             for (int j = 0; j < cmin; j++) {
4535                 if (atom.match(matcher, i, seq)) {
4536                     if (capture) {
4537                         groups[groupIndex] = i;
4538                         groups[groupIndex+1] = matcher.last;
4539                     }
4540                     i = matcher.last;
4541                 } else {
4542                     ret = false;
4543                     break;
4544                 }
4545             }
4546             if (ret) {
4547                 if (type == Qtype.GREEDY) {
4548                     ret = match0(matcher, i, cmin, seq);
4549                 } else if (type == Qtype.LAZY) {
4550                     ret = match1(matcher, i, cmin, seq);
4551                 } else {
4552                     ret = match2(matcher, i, cmin, seq);
4553                 }
4554             }
4555             if (!ret) {
4556                 locals[localIndex] = save0;
4557                 if (capture) {
4558                     groups[groupIndex] = save1;
4559                     groups[groupIndex+1] = save2;
4560                 }
4561             }
4562             return ret;
4563         }
4564         // Aggressive group match
4565         boolean match0(Matcher matcher, int i, int j, CharSequence seq) {
4566             // don't back off passing the starting "j"
4567             int min = j;
4568             int[] groups = matcher.groups;
4569             int save0 = 0;
4570             int save1 = 0;
4571             if (capture) {
4572                 save0 = groups[groupIndex];
4573                 save1 = groups[groupIndex+1];
4574             }
4575             for (;;) {
4576                 if (j >= cmax)
4577                     break;
4578                 if (!atom.match(matcher, i, seq))
4579                     break;
4580                 int k = matcher.last - i;
4581                 if (k <= 0) {
4582                     if (capture) {
4583                         groups[groupIndex] = i;
4584                         groups[groupIndex+1] = i + k;
4585                     }
4586                     i = i + k;
4587                     break;
4588                 }
4589                 for (;;) {
4590                     if (capture) {
4591                         groups[groupIndex] = i;
4592                         groups[groupIndex+1] = i + k;
4593                     }
4594                     i = i + k;
4595                     if (++j >= cmax)
4596                         break;
4597                     if (!atom.match(matcher, i, seq))
4598                         break;
4599                     if (i + k != matcher.last) {
4600                         if (match0(matcher, i, j, seq))
4601                             return true;
4602                         break;
4603                     }
4604                 }
4605                 while (j > min) {
4606                     if (next.match(matcher, i, seq)) {
4607                         if (capture) {
4608                             groups[groupIndex+1] = i;
4609                             groups[groupIndex] = i - k;
4610                         }
4611                         return true;
4612                     }
4613                     // backing off
4614                     i = i - k;
4615                     if (capture) {
4616                         groups[groupIndex+1] = i;
4617                         groups[groupIndex] = i - k;
4618                     }
4619                     j--;
4620 
4621                 }
4622                 break;
4623             }
4624             if (capture) {
4625                 groups[groupIndex] = save0;
4626                 groups[groupIndex+1] = save1;
4627             }
4628             return next.match(matcher, i, seq);
4629         }
4630         // Reluctant matching
4631         boolean match1(Matcher matcher, int i, int j, CharSequence seq) {
4632             for (;;) {
4633                 if (next.match(matcher, i, seq))
4634                     return true;
4635                 if (j >= cmax)
4636                     return false;
4637                 if (!atom.match(matcher, i, seq))
4638                     return false;
4639                 if (i == matcher.last)
4640                     return false;
4641                 if (capture) {
4642                     matcher.groups[groupIndex] = i;
4643                     matcher.groups[groupIndex+1] = matcher.last;
4644                 }
4645                 i = matcher.last;
4646                 j++;
4647             }
4648         }
4649         // Possessive matching
4650         boolean match2(Matcher matcher, int i, int j, CharSequence seq) {
4651             for (; j < cmax; j++) {
4652                 if (!atom.match(matcher, i, seq)) {
4653                     break;
4654                 }
4655                 if (capture) {
4656                     matcher.groups[groupIndex] = i;
4657                     matcher.groups[groupIndex+1] = matcher.last;
4658                 }
4659                 if (i == matcher.last) {
4660                     break;
4661                 }
4662                 i = matcher.last;
4663             }
4664             return next.match(matcher, i, seq);
4665         }
4666         boolean study(TreeInfo info) {
4667             // Save original info
4668             int minL = info.minLength;
4669             int maxL = info.maxLength;
4670             boolean maxV = info.maxValid;
4671             boolean detm = info.deterministic;
4672             info.reset();
4673 
4674             atom.study(info);
4675 
4676             int temp = info.minLength * cmin + minL;
4677             if (temp < minL) {
4678                 temp = 0xFFFFFFF; // Arbitrary large number
4679             }
4680             info.minLength = temp;
4681 
4682             if (maxV & info.maxValid) {
4683                 temp = info.maxLength * cmax + maxL;
4684                 info.maxLength = temp;
4685                 if (temp < maxL) {
4686                     info.maxValid = false;
4687                 }
4688             } else {
4689                 info.maxValid = false;
4690             }
4691 
4692             if (info.deterministic && cmin == cmax) {
4693                 info.deterministic = detm;
4694             } else {
4695                 info.deterministic = false;
4696             }
4697             return next.study(info);
4698         }
4699     }
4700 
4701     /**
4702      * A Guard node at the end of each atom node in a Branch. It
4703      * serves the purpose of chaining the "match" operation to
4704      * "next" but not the "study", so we can collect the TreeInfo
4705      * of each atom node without including the TreeInfo of the
4706      * "next".
4707      */
4708     static final class BranchConn extends Node {
4709         BranchConn() {}
4710         boolean match(Matcher matcher, int i, CharSequence seq) {
4711             return next.match(matcher, i, seq);
4712         }
4713         boolean study(TreeInfo info) {
4714             return info.deterministic;
4715         }
4716     }
4717 
4718     /**
4719      * Handles the branching of alternations. Note this is also used for
4720      * the ? quantifier to branch between the case where it matches once
4721      * and where it does not occur.
4722      */
4723     static final class Branch extends Node {
4724         Node[] atoms = new Node[2];
4725         int size = 2;
4726         Node conn;
4727         Branch(Node first, Node second, Node branchConn) {
4728             conn = branchConn;
4729             atoms[0] = first;
4730             atoms[1] = second;
4731         }
4732 
4733         void add(Node node) {
4734             if (size >= atoms.length) {
4735                 Node[] tmp = new Node[atoms.length*2];
4736                 System.arraycopy(atoms, 0, tmp, 0, atoms.length);
4737                 atoms = tmp;

4738             }
4739             atoms[size++] = node;
4740         }
4741 
4742         boolean match(Matcher matcher, int i, CharSequence seq) {
4743             for (int n = 0; n < size; n++) {
4744                 if (atoms[n] == null) {
4745                     if (conn.next.match(matcher, i, seq))
4746                         return true;
4747                 } else if (atoms[n].match(matcher, i, seq)) {
4748                     return true;
4749                 }
4750             }
4751             return false;
4752         }
4753 
4754         boolean study(TreeInfo info) {
4755             int minL = info.minLength;
4756             int maxL = info.maxLength;
4757             boolean maxV = info.maxValid;
4758 
4759             int minL2 = Integer.MAX_VALUE; //arbitrary large enough num
4760             int maxL2 = -1;
4761             for (int n = 0; n < size; n++) {
4762                 info.reset();
4763                 if (atoms[n] != null)
4764                     atoms[n].study(info);
4765                 minL2 = Math.min(minL2, info.minLength);
4766                 maxL2 = Math.max(maxL2, info.maxLength);
4767                 maxV = (maxV & info.maxValid);
4768             }
4769 
4770             minL += minL2;
4771             maxL += maxL2;
4772 
4773             info.reset();
4774             conn.next.study(info);
4775 
4776             info.minLength += minL;
4777             info.maxLength += maxL;
4778             info.maxValid &= maxV;
4779             info.deterministic = false;
4780             return false;
4781         }
4782     }
4783 
4784     /**
4785      * The GroupHead saves the location where the group begins in the locals
4786      * and restores them when the match is done.
4787      *
4788      * The matchRef is used when a reference to this group is accessed later
4789      * in the expression. The locals will have a negative value in them to
4790      * indicate that we do not want to unset the group if the reference
4791      * doesn't match.
4792      */
4793     static final class GroupHead extends Node {
4794         int localIndex;
4795         GroupTail tail;    // for debug/print only, match does not need to know
4796         GroupHead(int localCount) {
4797             localIndex = localCount;
4798         }
4799         boolean match(Matcher matcher, int i, CharSequence seq) {
4800             int save = matcher.locals[localIndex];
4801             matcher.locals[localIndex] = i;
4802             boolean ret = next.match(matcher, i, seq);
4803             matcher.locals[localIndex] = save;
4804             return ret;
4805         }
4806     }
4807 
4808     /**
4809      * The GroupTail handles the setting of group beginning and ending
4810      * locations when groups are successfully matched. It must also be able to
4811      * unset groups that have to be backed off of.
4812      *
4813      * The GroupTail node is also used when a previous group is referenced,
4814      * and in that case no group information needs to be set.
4815      */
4816     static final class GroupTail extends Node {
4817         int localIndex;
4818         int groupIndex;
4819         GroupTail(int localCount, int groupCount) {
4820             localIndex = localCount;
4821             groupIndex = groupCount + groupCount;
4822         }
4823         boolean match(Matcher matcher, int i, CharSequence seq) {
4824             int tmp = matcher.locals[localIndex];
4825             if (tmp >= 0) { // This is the normal group case.
4826                 // Save the group so we can unset it if it
4827                 // backs off of a match.
4828                 int groupStart = matcher.groups[groupIndex];
4829                 int groupEnd = matcher.groups[groupIndex+1];
4830 
4831                 matcher.groups[groupIndex] = tmp;
4832                 matcher.groups[groupIndex+1] = i;
4833                 if (next.match(matcher, i, seq)) {
4834                     return true;
4835                 }
4836                 matcher.groups[groupIndex] = groupStart;
4837                 matcher.groups[groupIndex+1] = groupEnd;
4838                 return false;
4839             } else {
4840                 // This is a group reference case. We don't need to save any
4841                 // group info because it isn't really a group.
4842                 matcher.last = i;
4843                 return true;
4844             }
4845         }
4846     }
4847 
4848     /**
4849      * This sets up a loop to handle a recursive quantifier structure.
4850      */
4851     static final class Prolog extends Node {
4852         Loop loop;
4853         Prolog(Loop loop) {
4854             this.loop = loop;
4855         }
4856         boolean match(Matcher matcher, int i, CharSequence seq) {
4857             return loop.matchInit(matcher, i, seq);
4858         }
4859         boolean study(TreeInfo info) {
4860             return loop.study(info);
4861         }
4862     }
4863 
4864     /**
4865      * Handles the repetition count for a greedy Curly. The matchInit
4866      * is called from the Prolog to save the index of where the group
4867      * beginning is stored. A zero length group check occurs in the
4868      * normal match but is skipped in the matchInit.
4869      */
4870     static class Loop extends Node {
4871         Node body;
4872         int countIndex; // local count index in matcher locals
4873         int beginIndex; // group beginning index
4874         int cmin, cmax;
4875         int posIndex;
4876         Loop(int countIndex, int beginIndex) {
4877             this.countIndex = countIndex;
4878             this.beginIndex = beginIndex;
4879             this.posIndex = -1;
4880         }
4881         boolean match(Matcher matcher, int i, CharSequence seq) {
4882             // Avoid infinite loop in zero-length case.
4883             if (i > matcher.locals[beginIndex]) {
4884                 int count = matcher.locals[countIndex];
4885 
4886                 // This block is for before we reach the minimum
4887                 // iterations required for the loop to match
4888                 if (count < cmin) {
4889                     matcher.locals[countIndex] = count + 1;
4890                     boolean b = body.match(matcher, i, seq);
4891                     // If match failed we must backtrack, so
4892                     // the loop count should NOT be incremented
4893                     if (!b)
4894                         matcher.locals[countIndex] = count;
4895                     // Return success or failure since we are under
4896                     // minimum
4897                     return b;
4898                 }
4899                 // This block is for after we have the minimum
4900                 // iterations required for the loop to match
4901                 if (count < cmax) {
4902                     // Let's check if we have already tried and failed
4903                     // at this starting position "i" in the past.
4904                     // If yes, then just return false wihtout trying
4905                     // again, to stop the exponential backtracking.
4906                     if (posIndex != -1 &&
4907                         matcher.localsPos[posIndex].contains(i)) {
4908                         return next.match(matcher, i, seq);
4909                     }
4910                     matcher.locals[countIndex] = count + 1;
4911                     boolean b = body.match(matcher, i, seq);
4912                     // If match failed we must backtrack, so
4913                     // the loop count should NOT be incremented
4914                     if (b)
4915                         return true;
4916                     matcher.locals[countIndex] = count;
4917                     // save the failed position
4918                     if (posIndex != -1) {
4919                         matcher.localsPos[posIndex].add(i);
4920                     }
4921                 }
4922             }
4923             return next.match(matcher, i, seq);
4924         }
4925         boolean matchInit(Matcher matcher, int i, CharSequence seq) {
4926             int save = matcher.locals[countIndex];
4927             boolean ret;
4928             if (posIndex != -1 && matcher.localsPos[posIndex] == null) {
4929                 matcher.localsPos[posIndex] = new IntHashSet();
4930             }
4931             if (0 < cmin) {
4932                 matcher.locals[countIndex] = 1;
4933                 ret = body.match(matcher, i, seq);
4934             } else if (0 < cmax) {
4935                 matcher.locals[countIndex] = 1;
4936                 ret = body.match(matcher, i, seq);
4937                 if (ret == false)
4938                     ret = next.match(matcher, i, seq);
4939             } else {
4940                 ret = next.match(matcher, i, seq);
4941             }
4942             matcher.locals[countIndex] = save;
4943             return ret;
4944         }
4945         boolean study(TreeInfo info) {
4946             info.maxValid = false;
4947             info.deterministic = false;
4948             return false;
4949         }
4950     }
4951 
4952     /**
4953      * Handles the repetition count for a reluctant Curly. The matchInit
4954      * is called from the Prolog to save the index of where the group
4955      * beginning is stored. A zero length group check occurs in the
4956      * normal match but is skipped in the matchInit.
4957      */
4958     static final class LazyLoop extends Loop {
4959         LazyLoop(int countIndex, int beginIndex) {
4960             super(countIndex, beginIndex);
4961         }
4962         boolean match(Matcher matcher, int i, CharSequence seq) {
4963             // Check for zero length group
4964             if (i > matcher.locals[beginIndex]) {
4965                 int count = matcher.locals[countIndex];
4966                 if (count < cmin) {
4967                     matcher.locals[countIndex] = count + 1;
4968                     boolean result = body.match(matcher, i, seq);
4969                     // If match failed we must backtrack, so
4970                     // the loop count should NOT be incremented
4971                     if (!result)
4972                         matcher.locals[countIndex] = count;
4973                     return result;
4974                 }
4975                 if (next.match(matcher, i, seq))
4976                     return true;
4977                 if (count < cmax) {
4978                     matcher.locals[countIndex] = count + 1;
4979                     boolean result = body.match(matcher, i, seq);
4980                     // If match failed we must backtrack, so
4981                     // the loop count should NOT be incremented
4982                     if (!result)
4983                         matcher.locals[countIndex] = count;
4984                     return result;
4985                 }
4986                 return false;
4987             }
4988             return next.match(matcher, i, seq);
4989         }
4990         boolean matchInit(Matcher matcher, int i, CharSequence seq) {
4991             int save = matcher.locals[countIndex];
4992             boolean ret = false;
4993             if (0 < cmin) {
4994                 matcher.locals[countIndex] = 1;
4995                 ret = body.match(matcher, i, seq);
4996             } else if (next.match(matcher, i, seq)) {
4997                 ret = true;
4998             } else if (0 < cmax) {
4999                 matcher.locals[countIndex] = 1;
5000                 ret = body.match(matcher, i, seq);
5001             }
5002             matcher.locals[countIndex] = save;
5003             return ret;
5004         }
5005         boolean study(TreeInfo info) {
5006             info.maxValid = false;
5007             info.deterministic = false;
5008             return false;
5009         }
5010     }
5011 
5012     /**
5013      * Refers to a group in the regular expression. Attempts to match
5014      * whatever the group referred to last matched.
5015      */
5016     static class BackRef extends Node {
5017         int groupIndex;
5018         BackRef(int groupCount) {
5019             super();
5020             groupIndex = groupCount + groupCount;
5021         }
5022         boolean match(Matcher matcher, int i, CharSequence seq) {
5023             int j = matcher.groups[groupIndex];
5024             int k = matcher.groups[groupIndex+1];
5025 
5026             int groupSize = k - j;
5027             // If the referenced group didn't match, neither can this
5028             if (j < 0)
5029                 return false;
5030 
5031             // If there isn't enough input left no match
5032             if (i + groupSize > matcher.to) {
5033                 matcher.hitEnd = true;
5034                 return false;
5035             }
5036             // Check each new char to make sure it matches what the group
5037             // referenced matched last time around
5038             for (int index=0; index<groupSize; index++)
5039                 if (seq.charAt(i+index) != seq.charAt(j+index))
5040                     return false;
5041 
5042             return next.match(matcher, i+groupSize, seq);
5043         }
5044         boolean study(TreeInfo info) {
5045             info.maxValid = false;
5046             return next.study(info);
5047         }
5048     }
5049 
5050     static class CIBackRef extends Node {
5051         int groupIndex;
5052         boolean doUnicodeCase;
5053         CIBackRef(int groupCount, boolean doUnicodeCase) {
5054             super();
5055             groupIndex = groupCount + groupCount;
5056             this.doUnicodeCase = doUnicodeCase;
5057         }
5058         boolean match(Matcher matcher, int i, CharSequence seq) {
5059             int j = matcher.groups[groupIndex];
5060             int k = matcher.groups[groupIndex+1];
5061 
5062             int groupSize = k - j;
5063 
5064             // If the referenced group didn't match, neither can this
5065             if (j < 0)
5066                 return false;
5067 
5068             // If there isn't enough input left no match
5069             if (i + groupSize > matcher.to) {
5070                 matcher.hitEnd = true;
5071                 return false;
5072             }
5073 
5074             // Check each new char to make sure it matches what the group
5075             // referenced matched last time around
5076             int x = i;
5077             for (int index=0; index<groupSize; index++) {
5078                 int c1 = Character.codePointAt(seq, x);
5079                 int c2 = Character.codePointAt(seq, j);
5080                 if (c1 != c2) {
5081                     if (doUnicodeCase) {
5082                         int cc1 = Character.toUpperCase(c1);
5083                         int cc2 = Character.toUpperCase(c2);
5084                         if (cc1 != cc2 &&
5085                             Character.toLowerCase(cc1) !=
5086                             Character.toLowerCase(cc2))
5087                             return false;
5088                     } else {
5089                         if (ASCII.toLower(c1) != ASCII.toLower(c2))
5090                             return false;
5091                     }
5092                 }
5093                 x += Character.charCount(c1);
5094                 j += Character.charCount(c2);
5095             }
5096 
5097             return next.match(matcher, i+groupSize, seq);
5098         }
5099         boolean study(TreeInfo info) {
5100             info.maxValid = false;
5101             return next.study(info);
5102         }
5103     }
5104 
5105     /**
5106      * Searches until the next instance of its atom. This is useful for
5107      * finding the atom efficiently without passing an instance of it
5108      * (greedy problem) and without a lot of wasted search time (reluctant
5109      * problem).
5110      */
5111     static final class First extends Node {
5112         Node atom;
5113         First(Node node) {
5114             this.atom = BnM.optimize(node);
5115         }
5116         boolean match(Matcher matcher, int i, CharSequence seq) {
5117             if (atom instanceof BnM) {
5118                 return atom.match(matcher, i, seq)
5119                     && next.match(matcher, matcher.last, seq);
5120             }
5121             for (;;) {
5122                 if (i > matcher.to) {
5123                     matcher.hitEnd = true;
5124                     return false;
5125                 }
5126                 if (atom.match(matcher, i, seq)) {
5127                     return next.match(matcher, matcher.last, seq);
5128                 }
5129                 i += countChars(seq, i, 1);
5130                 matcher.first++;
5131             }
5132         }
5133         boolean study(TreeInfo info) {
5134             atom.study(info);
5135             info.maxValid = false;
5136             info.deterministic = false;
5137             return next.study(info);
5138         }
5139     }
5140 
5141     /**
5142      * Zero width positive lookahead.
5143      */
5144     static final class Pos extends Node {
5145         Node cond;
5146         Pos(Node cond) {
5147             this.cond = cond;
5148         }
5149         boolean match(Matcher matcher, int i, CharSequence seq) {
5150             int savedTo = matcher.to;
5151             boolean conditionMatched;
5152 
5153             // Relax transparent region boundaries for lookahead
5154             if (matcher.transparentBounds)
5155                 matcher.to = matcher.getTextLength();
5156             try {
5157                 conditionMatched = cond.match(matcher, i, seq);
5158             } finally {
5159                 // Reinstate region boundaries
5160                 matcher.to = savedTo;
5161             }
5162             return conditionMatched && next.match(matcher, i, seq);
5163         }
5164     }
5165 
5166     /**
5167      * Zero width negative lookahead.
5168      */
5169     static final class Neg extends Node {
5170         Node cond;
5171         Neg(Node cond) {
5172             this.cond = cond;
5173         }
5174         boolean match(Matcher matcher, int i, CharSequence seq) {
5175             int savedTo = matcher.to;
5176             boolean conditionMatched;
5177 
5178             // Relax transparent region boundaries for lookahead
5179             if (matcher.transparentBounds)
5180                 matcher.to = matcher.getTextLength();
5181             try {
5182                 if (i < matcher.to) {
5183                     conditionMatched = !cond.match(matcher, i, seq);
5184                 } else {
5185                     // If a negative lookahead succeeds then more input
5186                     // could cause it to fail!
5187                     matcher.requireEnd = true;
5188                     conditionMatched = !cond.match(matcher, i, seq);
5189                 }
5190             } finally {
5191                 // Reinstate region boundaries
5192                 matcher.to = savedTo;
5193             }
5194             return conditionMatched && next.match(matcher, i, seq);
5195         }
5196     }
5197 
5198     /**
5199      * For use with lookbehinds; matches the position where the lookbehind
5200      * was encountered.
5201      */
5202     static class LookBehindEndNode extends Node {
5203         private LookBehindEndNode() {} // Singleton
5204 
5205         static LookBehindEndNode INSTANCE = new LookBehindEndNode();
5206 
5207         boolean match(Matcher matcher, int i, CharSequence seq) {
5208             return i == matcher.lookbehindTo;
5209         }
5210     }
5211 
5212     /**
5213      * Zero width positive lookbehind.
5214      */
5215     static class Behind extends Node {
5216         Node cond;
5217         int rmax, rmin;
5218         Behind(Node cond, int rmax, int rmin) {
5219             this.cond = cond;
5220             this.rmax = rmax;
5221             this.rmin = rmin;
5222         }
5223 
5224         boolean match(Matcher matcher, int i, CharSequence seq) {
5225             int savedFrom = matcher.from;
5226             boolean conditionMatched = false;
5227             int startIndex = (!matcher.transparentBounds) ?
5228                              matcher.from : 0;
5229             int from = Math.max(i - rmax, startIndex);
5230             // Set end boundary
5231             int savedLBT = matcher.lookbehindTo;
5232             matcher.lookbehindTo = i;
5233             // Relax transparent region boundaries for lookbehind
5234             if (matcher.transparentBounds)
5235                 matcher.from = 0;
5236             for (int j = i - rmin; !conditionMatched && j >= from; j--) {
5237                 conditionMatched = cond.match(matcher, j, seq);
5238             }
5239             matcher.from = savedFrom;
5240             matcher.lookbehindTo = savedLBT;
5241             return conditionMatched && next.match(matcher, i, seq);
5242         }
5243     }
5244 
5245     /**
5246      * Zero width positive lookbehind, including supplementary
5247      * characters or unpaired surrogates.
5248      */
5249     static final class BehindS extends Behind {
5250         BehindS(Node cond, int rmax, int rmin) {
5251             super(cond, rmax, rmin);
5252         }
5253         boolean match(Matcher matcher, int i, CharSequence seq) {
5254             int rmaxChars = countChars(seq, i, -rmax);
5255             int rminChars = countChars(seq, i, -rmin);
5256             int savedFrom = matcher.from;
5257             int startIndex = (!matcher.transparentBounds) ?
5258                              matcher.from : 0;
5259             boolean conditionMatched = false;
5260             int from = Math.max(i - rmaxChars, startIndex);
5261             // Set end boundary
5262             int savedLBT = matcher.lookbehindTo;
5263             matcher.lookbehindTo = i;
5264             // Relax transparent region boundaries for lookbehind
5265             if (matcher.transparentBounds)
5266                 matcher.from = 0;
5267 
5268             for (int j = i - rminChars;
5269                  !conditionMatched && j >= from;
5270                  j -= j>from ? countChars(seq, j, -1) : 1) {
5271                 conditionMatched = cond.match(matcher, j, seq);
5272             }
5273             matcher.from = savedFrom;
5274             matcher.lookbehindTo = savedLBT;
5275             return conditionMatched && next.match(matcher, i, seq);
5276         }
5277     }
5278 
5279     /**
5280      * Zero width negative lookbehind.
5281      */
5282     static class NotBehind extends Node {
5283         Node cond;
5284         int rmax, rmin;
5285         NotBehind(Node cond, int rmax, int rmin) {
5286             this.cond = cond;
5287             this.rmax = rmax;
5288             this.rmin = rmin;
5289         }
5290 
5291         boolean match(Matcher matcher, int i, CharSequence seq) {
5292             int savedLBT = matcher.lookbehindTo;
5293             int savedFrom = matcher.from;
5294             boolean conditionMatched = false;
5295             int startIndex = (!matcher.transparentBounds) ?
5296                              matcher.from : 0;
5297             int from = Math.max(i - rmax, startIndex);
5298             matcher.lookbehindTo = i;
5299             // Relax transparent region boundaries for lookbehind
5300             if (matcher.transparentBounds)
5301                 matcher.from = 0;
5302             for (int j = i - rmin; !conditionMatched && j >= from; j--) {
5303                 conditionMatched = cond.match(matcher, j, seq);
5304             }
5305             // Reinstate region boundaries
5306             matcher.from = savedFrom;
5307             matcher.lookbehindTo = savedLBT;
5308             return !conditionMatched && next.match(matcher, i, seq);
5309         }
5310     }
5311 
5312     /**
5313      * Zero width negative lookbehind, including supplementary
5314      * characters or unpaired surrogates.
5315      */
5316     static final class NotBehindS extends NotBehind {
5317         NotBehindS(Node cond, int rmax, int rmin) {
5318             super(cond, rmax, rmin);
5319         }
5320         boolean match(Matcher matcher, int i, CharSequence seq) {
5321             int rmaxChars = countChars(seq, i, -rmax);
5322             int rminChars = countChars(seq, i, -rmin);
5323             int savedFrom = matcher.from;
5324             int savedLBT = matcher.lookbehindTo;
5325             boolean conditionMatched = false;
5326             int startIndex = (!matcher.transparentBounds) ?
5327                              matcher.from : 0;
5328             int from = Math.max(i - rmaxChars, startIndex);
5329             matcher.lookbehindTo = i;
5330             // Relax transparent region boundaries for lookbehind
5331             if (matcher.transparentBounds)
5332                 matcher.from = 0;
5333             for (int j = i - rminChars;
5334                  !conditionMatched && j >= from;
5335                  j -= j>from ? countChars(seq, j, -1) : 1) {
5336                 conditionMatched = cond.match(matcher, j, seq);
5337             }
5338             //Reinstate region boundaries
5339             matcher.from = savedFrom;
5340             matcher.lookbehindTo = savedLBT;
5341             return !conditionMatched && next.match(matcher, i, seq);
5342         }
5343     }
5344 
5345     /**
5346      * Handles word boundaries. Includes a field to allow this one class to
5347      * deal with the different types of word boundaries we can match. The word
5348      * characters include underscores, letters, and digits. Non spacing marks
5349      * can are also part of a word if they have a base character, otherwise
5350      * they are ignored for purposes of finding word boundaries.
5351      */
5352     static final class Bound extends Node {
5353         static int LEFT = 0x1;
5354         static int RIGHT= 0x2;
5355         static int BOTH = 0x3;
5356         static int NONE = 0x4;
5357         int type;
5358         boolean useUWORD;
5359         Bound(int n, boolean useUWORD) {
5360             type = n;
5361             this.useUWORD = useUWORD;
5362         }
5363 
5364         boolean isWord(int ch) {
5365             return useUWORD ? CharPredicates.WORD().is(ch)
5366                             : (ch == '_' || Character.isLetterOrDigit(ch));
5367         }
5368 
5369         int check(Matcher matcher, int i, CharSequence seq) {
5370             int ch;
5371             boolean left = false;
5372             int startIndex = matcher.from;
5373             int endIndex = matcher.to;
5374             if (matcher.transparentBounds) {
5375                 startIndex = 0;
5376                 endIndex = matcher.getTextLength();
5377             }
5378             if (i > startIndex) {
5379                 ch = Character.codePointBefore(seq, i);
5380                 left = (isWord(ch) ||
5381                     ((Character.getType(ch) == Character.NON_SPACING_MARK)
5382                      && hasBaseCharacter(matcher, i-1, seq)));
5383             }
5384             boolean right = false;
5385             if (i < endIndex) {
5386                 ch = Character.codePointAt(seq, i);
5387                 right = (isWord(ch) ||
5388                     ((Character.getType(ch) == Character.NON_SPACING_MARK)
5389                      && hasBaseCharacter(matcher, i, seq)));
5390             } else {
5391                 // Tried to access char past the end
5392                 matcher.hitEnd = true;
5393                 // The addition of another char could wreck a boundary
5394                 matcher.requireEnd = true;
5395             }
5396             return ((left ^ right) ? (right ? LEFT : RIGHT) : NONE);
5397         }
5398         boolean match(Matcher matcher, int i, CharSequence seq) {
5399             return (check(matcher, i, seq) & type) > 0
5400                 && next.match(matcher, i, seq);
5401         }
5402     }
5403 
5404     /**
5405      * Non spacing marks only count as word characters in bounds calculations
5406      * if they have a base character.
5407      */
5408     private static boolean hasBaseCharacter(Matcher matcher, int i,
5409                                             CharSequence seq)
5410     {
5411         int start = (!matcher.transparentBounds) ?
5412             matcher.from : 0;
5413         for (int x=i; x >= start; x--) {
5414             int ch = Character.codePointAt(seq, x);
5415             if (Character.isLetterOrDigit(ch))
5416                 return true;
5417             if (Character.getType(ch) == Character.NON_SPACING_MARK)
5418                 continue;
5419             return false;
5420         }
5421         return false;
5422     }
5423 
5424     /**
5425      * Attempts to match a slice in the input using the Boyer-Moore string
5426      * matching algorithm. The algorithm is based on the idea that the
5427      * pattern can be shifted farther ahead in the search text if it is
5428      * matched right to left.
5429      * <p>
5430      * The pattern is compared to the input one character at a time, from
5431      * the rightmost character in the pattern to the left. If the characters
5432      * all match the pattern has been found. If a character does not match,
5433      * the pattern is shifted right a distance that is the maximum of two
5434      * functions, the bad character shift and the good suffix shift. This
5435      * shift moves the attempted match position through the input more
5436      * quickly than a naive one position at a time check.
5437      * <p>
5438      * The bad character shift is based on the character from the text that
5439      * did not match. If the character does not appear in the pattern, the
5440      * pattern can be shifted completely beyond the bad character. If the
5441      * character does occur in the pattern, the pattern can be shifted to
5442      * line the pattern up with the next occurrence of that character.
5443      * <p>
5444      * The good suffix shift is based on the idea that some subset on the right
5445      * side of the pattern has matched. When a bad character is found, the
5446      * pattern can be shifted right by the pattern length if the subset does
5447      * not occur again in pattern, or by the amount of distance to the
5448      * next occurrence of the subset in the pattern.
5449      *
5450      * Boyer-Moore search methods adapted from code by Amy Yu.
5451      */
5452     static class BnM extends Node {
5453         int[] buffer;
5454         int[] lastOcc;
5455         int[] optoSft;
5456 
5457         /**
5458          * Pre calculates arrays needed to generate the bad character
5459          * shift and the good suffix shift. Only the last seven bits
5460          * are used to see if chars match; This keeps the tables small
5461          * and covers the heavily used ASCII range, but occasionally
5462          * results in an aliased match for the bad character shift.
5463          */
5464         static Node optimize(Node node) {
5465             if (!(node instanceof Slice)) {
5466                 return node;
5467             }
5468 
5469             int[] src = ((Slice) node).buffer;
5470             int patternLength = src.length;
5471             // The BM algorithm requires a bit of overhead;
5472             // If the pattern is short don't use it, since
5473             // a shift larger than the pattern length cannot
5474             // be used anyway.
5475             if (patternLength < 4) {
5476                 return node;
5477             }
5478             int i, j;
5479             int[] lastOcc = new int[128];
5480             int[] optoSft = new int[patternLength];
5481             // Precalculate part of the bad character shift
5482             // It is a table for where in the pattern each
5483             // lower 7-bit value occurs
5484             for (i = 0; i < patternLength; i++) {
5485                 lastOcc[src[i]&0x7F] = i + 1;
5486             }
5487             // Precalculate the good suffix shift
5488             // i is the shift amount being considered
5489 NEXT:       for (i = patternLength; i > 0; i--) {
5490                 // j is the beginning index of suffix being considered
5491                 for (j = patternLength - 1; j >= i; j--) {
5492                     // Testing for good suffix
5493                     if (src[j] == src[j-i]) {
5494                         // src[j..len] is a good suffix
5495                         optoSft[j-1] = i;
5496                     } else {
5497                         // No match. The array has already been
5498                         // filled up with correct values before.
5499                         continue NEXT;
5500                     }
5501                 }
5502                 // This fills up the remaining of optoSft
5503                 // any suffix can not have larger shift amount
5504                 // then its sub-suffix. Why???
5505                 while (j > 0) {
5506                     optoSft[--j] = i;
5507                 }
5508             }
5509             // Set the guard value because of unicode compression
5510             optoSft[patternLength-1] = 1;
5511             if (node instanceof SliceS)
5512                 return new BnMS(src, lastOcc, optoSft, node.next);
5513             return new BnM(src, lastOcc, optoSft, node.next);
5514         }
5515         BnM(int[] src, int[] lastOcc, int[] optoSft, Node next) {
5516             this.buffer = src;
5517             this.lastOcc = lastOcc;
5518             this.optoSft = optoSft;
5519             this.next = next;
5520         }
5521         boolean match(Matcher matcher, int i, CharSequence seq) {
5522             int[] src = buffer;
5523             int patternLength = src.length;
5524             int last = matcher.to - patternLength;
5525 
5526             // Loop over all possible match positions in text
5527 NEXT:       while (i <= last) {
5528                 // Loop over pattern from right to left
5529                 for (int j = patternLength - 1; j >= 0; j--) {
5530                     int ch = seq.charAt(i+j);
5531                     if (ch != src[j]) {
5532                         // Shift search to the right by the maximum of the
5533                         // bad character shift and the good suffix shift
5534                         i += Math.max(j + 1 - lastOcc[ch&0x7F], optoSft[j]);
5535                         continue NEXT;
5536                     }
5537                 }
5538                 // Entire pattern matched starting at i
5539                 matcher.first = i;
5540                 boolean ret = next.match(matcher, i + patternLength, seq);
5541                 if (ret) {
5542                     matcher.first = i;
5543                     matcher.groups[0] = matcher.first;
5544                     matcher.groups[1] = matcher.last;
5545                     return true;
5546                 }
5547                 i++;
5548             }
5549             // BnM is only used as the leading node in the unanchored case,
5550             // and it replaced its Start() which always searches to the end
5551             // if it doesn't find what it's looking for, so hitEnd is true.
5552             matcher.hitEnd = true;
5553             return false;
5554         }
5555         boolean study(TreeInfo info) {
5556             info.minLength += buffer.length;
5557             info.maxValid = false;
5558             return next.study(info);
5559         }
5560     }
5561 
5562     /**
5563      * Supplementary support version of BnM(). Unpaired surrogates are
5564      * also handled by this class.
5565      */
5566     static final class BnMS extends BnM {
5567         int lengthInChars;
5568 
5569         BnMS(int[] src, int[] lastOcc, int[] optoSft, Node next) {
5570             super(src, lastOcc, optoSft, next);
5571             for (int cp : buffer) {
5572                 lengthInChars += Character.charCount(cp);
5573             }
5574         }
5575         boolean match(Matcher matcher, int i, CharSequence seq) {
5576             int[] src = buffer;
5577             int patternLength = src.length;
5578             int last = matcher.to - lengthInChars;
5579 
5580             // Loop over all possible match positions in text
5581 NEXT:       while (i <= last) {
5582                 // Loop over pattern from right to left
5583                 int ch;
5584                 for (int j = countChars(seq, i, patternLength), x = patternLength - 1;
5585                      j > 0; j -= Character.charCount(ch), x--) {
5586                     ch = Character.codePointBefore(seq, i+j);
5587                     if (ch != src[x]) {
5588                         // Shift search to the right by the maximum of the
5589                         // bad character shift and the good suffix shift
5590                         int n = Math.max(x + 1 - lastOcc[ch&0x7F], optoSft[x]);
5591                         i += countChars(seq, i, n);
5592                         continue NEXT;
5593                     }
5594                 }
5595                 // Entire pattern matched starting at i
5596                 matcher.first = i;
5597                 boolean ret = next.match(matcher, i + lengthInChars, seq);
5598                 if (ret) {
5599                     matcher.first = i;
5600                     matcher.groups[0] = matcher.first;
5601                     matcher.groups[1] = matcher.last;
5602                     return true;
5603                 }
5604                 i += countChars(seq, i, 1);
5605             }
5606             matcher.hitEnd = true;
5607             return false;
5608         }
5609     }
5610 
5611     @FunctionalInterface
5612     static interface CharPredicate {
5613         boolean is(int ch);
5614 
5615         default CharPredicate and(CharPredicate p) {
5616             return ch -> is(ch) && p.is(ch);
5617         }
5618         default CharPredicate union(CharPredicate p) {
5619             return ch -> is(ch) || p.is(ch);
5620         }
5621         default CharPredicate union(CharPredicate p1,
5622                                     CharPredicate p2 ) {
5623             return ch -> is(ch) || p1.is(ch) || p2.is(ch);
5624         }
5625         default CharPredicate negate() {
5626             return ch -> !is(ch);
5627         }
5628     }
5629 
5630     static interface BmpCharPredicate extends CharPredicate {
5631 
5632         default CharPredicate and(CharPredicate p) {
5633             if (p instanceof BmpCharPredicate)
5634                 return (BmpCharPredicate)(ch -> is(ch) && p.is(ch));
5635             return ch -> is(ch) && p.is(ch);
5636         }
5637         default CharPredicate union(CharPredicate p) {
5638             if (p instanceof BmpCharPredicate)
5639                 return (BmpCharPredicate)(ch -> is(ch) || p.is(ch));
5640             return ch -> is(ch) || p.is(ch);
5641         }
5642         static CharPredicate union(CharPredicate... predicates) {
5643             CharPredicate cp = ch -> {
5644                 for (CharPredicate p : predicates) {
5645                     if (!p.is(ch))
5646                         return false;
5647                 }
5648                 return true;
5649             };
5650             for (CharPredicate p : predicates) {
5651                 if (! (p instanceof BmpCharPredicate))
5652                     return cp;
5653             }
5654             return (BmpCharPredicate)cp;
5655         }
5656     }
5657 
5658     /**
5659      * matches a Perl vertical whitespace
5660      */
5661     static BmpCharPredicate VertWS() {
5662         return cp -> (cp >= 0x0A && cp <= 0x0D) ||
5663             cp == 0x85 || cp == 0x2028 || cp == 0x2029;
5664     }
5665 
5666     /**
5667      * matches a Perl horizontal whitespace
5668      */
5669     static BmpCharPredicate HorizWS() {
5670         return cp ->
5671             cp == 0x09 || cp == 0x20 || cp == 0xa0 || cp == 0x1680 ||
5672             cp == 0x180e || cp >= 0x2000 && cp <= 0x200a ||  cp == 0x202f ||
5673             cp == 0x205f || cp == 0x3000;
5674     }
5675 
5676     /**
5677      *  for the Unicode category ALL and the dot metacharacter when
5678      *  in dotall mode.
5679      */
5680     static CharPredicate ALL() {
5681         return ch -> true;
5682     }
5683 
5684     /**
5685      * for the dot metacharacter when dotall is not enabled.
5686      */
5687     static CharPredicate DOT() {
5688         return ch ->
5689             (ch != '\n' && ch != '\r'
5690             && (ch|1) != '\u2029'
5691             && ch != '\u0085');
5692     }
5693 
5694     /**
5695      *  the dot metacharacter when dotall is not enabled but UNIX_LINES is enabled.
5696      */
5697     static CharPredicate UNIXDOT() {
5698         return ch ->  ch != '\n';
5699     }
5700 
5701     /**
5702      * Indicate that matches a Supplementary Unicode character
5703      */
5704     static CharPredicate SingleS(int c) {
5705         return ch -> ch == c;
5706     }
5707 
5708     /**
5709      * A bmp/optimized predicate of single
5710      */
5711     static BmpCharPredicate Single(int c) {
5712         return ch -> ch == c;
5713     }
5714 
5715     /**
5716      * Case insensitive matches a given BMP character
5717      */
5718     static BmpCharPredicate SingleI(int lower, int upper) {
5719         return ch -> ch == lower || ch == upper;
5720     }
5721 
5722     /**
5723      * Unicode case insensitive matches a given Unicode character
5724      */
5725     static CharPredicate SingleU(int lower) {
5726         return ch -> lower == ch ||
5727                      lower == Character.toLowerCase(Character.toUpperCase(ch));
5728     }
5729 
5730     private static boolean inRange(int lower, int ch, int upper) {
5731         return lower <= ch && ch <= upper;
5732     }
5733 
5734     /**
5735      * Charactrs within a explicit value range
5736      */
5737     static CharPredicate Range(int lower, int upper) {
5738         if (upper < Character.MIN_HIGH_SURROGATE ||
5739             lower > Character.MAX_HIGH_SURROGATE &&
5740             upper < Character.MIN_SUPPLEMENTARY_CODE_POINT)
5741             return (BmpCharPredicate)(ch -> inRange(lower, ch, upper));
5742         return ch -> inRange(lower, ch, upper);
5743     }
5744 
5745    /**
5746     * Charactrs within a explicit value range in a case insensitive manner.
5747     */
5748     static CharPredicate CIRange(int lower, int upper) {
5749         return ch -> inRange(lower, ch, upper) ||
5750                      ASCII.isAscii(ch) &&
5751                      (inRange(lower, ASCII.toUpper(ch), upper) ||
5752                       inRange(lower, ASCII.toLower(ch), upper));
5753     }
5754 
5755     static CharPredicate CIRangeU(int lower, int upper) {
5756         return ch -> {
5757             if (inRange(lower, ch, upper))
5758                 return true;
5759             int up = Character.toUpperCase(ch);
5760             return inRange(lower, up, upper) ||
5761                    inRange(lower, Character.toLowerCase(up), upper);
5762         };
5763     }
5764 
5765     /**
5766      *  This must be the very first initializer.
5767      */
5768     static final Node accept = new Node();
5769 
5770     static final Node lastAccept = new LastNode();
5771 
5772     /**
5773      * Creates a predicate that tests if this pattern is found in a given input
5774      * string.
5775      *
5776      * @apiNote
5777      * This method creates a predicate that behaves as if it creates a matcher
5778      * from the input sequence and then calls {@code find}, for example a
5779      * predicate of the form:
5780      * <pre>{@code
5781      *   s -> matcher(s).find();
5782      * }</pre>
5783      *
5784      * @return  The predicate which can be used for finding a match on a
5785      *          subsequence of a string
5786      * @since   1.8
5787      * @see     Matcher#find
5788      */
5789     public Predicate<String> asPredicate() {
5790         return s -> matcher(s).find();
5791     }
5792 
5793     /**
5794      * Creates a predicate that tests if this pattern matches a given input string.
5795      *
5796      * @apiNote
5797      * This method creates a predicate that behaves as if it creates a matcher
5798      * from the input sequence and then calls {@code matches}, for example a
5799      * predicate of the form:
5800      * <pre>{@code
5801      *   s -> matcher(s).matches();
5802      * }</pre>
5803      *
5804      * @return  The predicate which can be used for matching an input string
5805      *          against this pattern.
5806      * @since   11
5807      * @see     Matcher#matches
5808      */
5809     public Predicate<String> asMatchPredicate() {
5810         return s -> matcher(s).matches();
5811     }
5812 
5813     /**
5814      * Creates a stream from the given input sequence around matches of this
5815      * pattern.
5816      *
5817      * <p> The stream returned by this method contains each substring of the
5818      * input sequence that is terminated by another subsequence that matches
5819      * this pattern or is terminated by the end of the input sequence.  The
5820      * substrings in the stream are in the order in which they occur in the
5821      * input. Trailing empty strings will be discarded and not encountered in
5822      * the stream.
5823      *
5824      * <p> If this pattern does not match any subsequence of the input then
5825      * the resulting stream has just one element, namely the input sequence in
5826      * string form.
5827      *
5828      * <p> When there is a positive-width match at the beginning of the input
5829      * sequence then an empty leading substring is included at the beginning
5830      * of the stream. A zero-width match at the beginning however never produces
5831      * such empty leading substring.
5832      *
5833      * <p> If the input sequence is mutable, it must remain constant during the
5834      * execution of the terminal stream operation.  Otherwise, the result of the
5835      * terminal stream operation is undefined.
5836      *
5837      * @param   input
5838      *          The character sequence to be split
5839      *
5840      * @return  The stream of strings computed by splitting the input
5841      *          around matches of this pattern
5842      * @see     #split(CharSequence)
5843      * @since   1.8
5844      */
5845     public Stream<String> splitAsStream(final CharSequence input) {
5846         class MatcherIterator implements Iterator<String> {
5847             private Matcher matcher;
5848             // The start position of the next sub-sequence of input
5849             // when current == input.length there are no more elements
5850             private int current;
5851             // null if the next element, if any, needs to obtained
5852             private String nextElement;
5853             // > 0 if there are N next empty elements
5854             private int emptyElementCount;
5855 
5856             public String next() {
5857                 if (!hasNext())
5858                     throw new NoSuchElementException();
5859 
5860                 if (emptyElementCount == 0) {
5861                     String n = nextElement;
5862                     nextElement = null;
5863                     return n;
5864                 } else {
5865                     emptyElementCount--;
5866                     return "";
5867                 }
5868             }
5869 
5870             public boolean hasNext() {
5871                 if (matcher == null) {
5872                     matcher = matcher(input);
5873                     // If the input is an empty string then the result can only be a
5874                     // stream of the input.  Induce that by setting the empty
5875                     // element count to 1
5876                     emptyElementCount = input.length() == 0 ? 1 : 0;
5877                 }
5878                 if (nextElement != null || emptyElementCount > 0)
5879                     return true;
5880 
5881                 if (current == input.length())
5882                     return false;
5883 
5884                 // Consume the next matching element
5885                 // Count sequence of matching empty elements
5886                 while (matcher.find()) {
5887                     nextElement = input.subSequence(current, matcher.start()).toString();
5888                     current = matcher.end();
5889                     if (!nextElement.isEmpty()) {
5890                         return true;
5891                     } else if (current > 0) { // no empty leading substring for zero-width
5892                                               // match at the beginning of the input
5893                         emptyElementCount++;
5894                     }
5895                 }
5896 
5897                 // Consume last matching element
5898                 nextElement = input.subSequence(current, input.length()).toString();
5899                 current = input.length();
5900                 if (!nextElement.isEmpty()) {
5901                     return true;
5902                 } else {
5903                     // Ignore a terminal sequence of matching empty elements
5904                     emptyElementCount = 0;
5905                     nextElement = null;
5906                     return false;
5907                 }
5908             }
5909         }
5910         return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
5911                 new MatcherIterator(), Spliterator.ORDERED | Spliterator.NONNULL), false);
5912     }
5913 }
--- EOF ---