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