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