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