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