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