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