• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This code is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License version 2 only, as
8  * published by the Free Software Foundation.  Oracle designates this
9  * particular file as subject to the "Classpath" exception as provided
10  * by Oracle in the LICENSE file that accompanied this code.
11  *
12  * This code is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15  * version 2 for more details (a copy is included in the LICENSE file that
16  * accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License version
19  * 2 along with this work; if not, write to the Free Software Foundation,
20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21  *
22  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
23  * or visit www.oracle.com if you need additional information or have any
24  * questions.
25  */
26 
27 package java.util.regex;
28 
29 import dalvik.annotation.optimization.ReachabilitySensitive;
30 import dalvik.system.VMRuntime;
31 
32 import libcore.util.NativeAllocationRegistry;
33 
34 import java.util.Iterator;
35 import java.util.ArrayList;
36 import java.util.NoSuchElementException;
37 import java.util.Spliterator;
38 import java.util.Spliterators;
39 import java.util.function.Predicate;
40 import java.util.stream.Stream;
41 import java.util.stream.StreamSupport;
42 
43 import libcore.util.EmptyArray;
44 
45 // Android-changed: Document that named capturing is only available from API 26.
46 // Android-changed: Android always uses unicode character classes.
47 // UNICODE_CHARACTER_CLASS has no effect on Android.
48 /**
49  * A compiled representation of a regular expression.
50  *
51  * <p> A regular expression, specified as a string, must first be compiled into
52  * an instance of this class.  The resulting pattern can then be used to create
53  * a {@link Matcher} object that can match arbitrary {@linkplain
54  * java.lang.CharSequence character sequences} against the regular
55  * expression.  All of the state involved in performing a match resides in the
56  * matcher, so many matchers can share the same pattern.
57  *
58  * <p> A typical invocation sequence is thus
59  *
60  * <blockquote><pre>
61  * Pattern p = Pattern.{@link #compile compile}("a*b");
62  * Matcher m = p.{@link #matcher matcher}("aaaaab");
63  * boolean b = m.{@link Matcher#matches matches}();</pre></blockquote>
64  *
65  * <p> A {@link #matches matches} method is defined by this class as a
66  * convenience for when a regular expression is used just once.  This method
67  * compiles an expression and matches an input sequence against it in a single
68  * invocation.  The statement
69  *
70  * <blockquote><pre>
71  * boolean b = Pattern.matches("a*b", "aaaaab");</pre></blockquote>
72  *
73  * is equivalent to the three statements above, though for repeated matches it
74  * is less efficient since it does not allow the compiled pattern to be reused.
75  *
76  * <p> Instances of this class are immutable and are safe for use by multiple
77  * concurrent threads.  Instances of the {@link Matcher} class are not safe for
78  * such use.
79  *
80  *
81  * <h3><a name="sum">Summary of regular-expression constructs</a></h3>
82  *
83  * <table border="0" cellpadding="1" cellspacing="0"
84  *  summary="Regular expression constructs, and what they match">
85  *
86  * <tr align="left">
87  * <th align="left" id="construct">Construct</th>
88  * <th align="left" id="matches">Matches</th>
89  * </tr>
90  *
91  * <tr><th>&nbsp;</th></tr>
92  * <tr align="left"><th colspan="2" id="characters">Characters</th></tr>
93  *
94  * <tr><td valign="top" headers="construct characters"><i>x</i></td>
95  *     <td headers="matches">The character <i>x</i></td></tr>
96  * <tr><td valign="top" headers="construct characters"><tt>\\</tt></td>
97  *     <td headers="matches">The backslash character</td></tr>
98  * <tr><td valign="top" headers="construct characters"><tt>\0</tt><i>n</i></td>
99  *     <td headers="matches">The character with octal value <tt>0</tt><i>n</i>
100  *         (0&nbsp;<tt>&lt;=</tt>&nbsp;<i>n</i>&nbsp;<tt>&lt;=</tt>&nbsp;7)</td></tr>
101  * <tr><td valign="top" headers="construct characters"><tt>\0</tt><i>nn</i></td>
102  *     <td headers="matches">The character with octal value <tt>0</tt><i>nn</i>
103  *         (0&nbsp;<tt>&lt;=</tt>&nbsp;<i>n</i>&nbsp;<tt>&lt;=</tt>&nbsp;7)</td></tr>
104  * <tr><td valign="top" headers="construct characters"><tt>\0</tt><i>mnn</i></td>
105  *     <td headers="matches">The character with octal value <tt>0</tt><i>mnn</i>
106  *         (0&nbsp;<tt>&lt;=</tt>&nbsp;<i>m</i>&nbsp;<tt>&lt;=</tt>&nbsp;3,
107  *         0&nbsp;<tt>&lt;=</tt>&nbsp;<i>n</i>&nbsp;<tt>&lt;=</tt>&nbsp;7)</td></tr>
108  * <tr><td valign="top" headers="construct characters"><tt>\x</tt><i>hh</i></td>
109  *     <td headers="matches">The character with hexadecimal&nbsp;value&nbsp;<tt>0x</tt><i>hh</i></td></tr>
110  * <tr><td valign="top" headers="construct characters"><tt>&#92;u</tt><i>hhhh</i></td>
111  *     <td headers="matches">The character with hexadecimal&nbsp;value&nbsp;<tt>0x</tt><i>hhhh</i></td></tr>
112  * <tr><td valign="top" headers="construct characters"><tt>&#92;x</tt><i>{h...h}</i></td>
113  *     <td headers="matches">The character with hexadecimal&nbsp;value&nbsp;<tt>0x</tt><i>h...h</i>
114  *         ({@link java.lang.Character#MIN_CODE_POINT Character.MIN_CODE_POINT}
115  *         &nbsp;&lt;=&nbsp;<tt>0x</tt><i>h...h</i>&nbsp;&lt;=&nbsp;
116  *          {@link java.lang.Character#MAX_CODE_POINT Character.MAX_CODE_POINT})</td></tr>
117  * <tr><td valign="top" headers="matches"><tt>\t</tt></td>
118  *     <td headers="matches">The tab character (<tt>'&#92;u0009'</tt>)</td></tr>
119  * <tr><td valign="top" headers="construct characters"><tt>\n</tt></td>
120  *     <td headers="matches">The newline (line feed) character (<tt>'&#92;u000A'</tt>)</td></tr>
121  * <tr><td valign="top" headers="construct characters"><tt>\r</tt></td>
122  *     <td headers="matches">The carriage-return character (<tt>'&#92;u000D'</tt>)</td></tr>
123  * <tr><td valign="top" headers="construct characters"><tt>\f</tt></td>
124  *     <td headers="matches">The form-feed character (<tt>'&#92;u000C'</tt>)</td></tr>
125  * <tr><td valign="top" headers="construct characters"><tt>\a</tt></td>
126  *     <td headers="matches">The alert (bell) character (<tt>'&#92;u0007'</tt>)</td></tr>
127  * <tr><td valign="top" headers="construct characters"><tt>\e</tt></td>
128  *     <td headers="matches">The escape character (<tt>'&#92;u001B'</tt>)</td></tr>
129  * <tr><td valign="top" headers="construct characters"><tt>\c</tt><i>x</i></td>
130  *     <td headers="matches">The control character corresponding to <i>x</i></td></tr>
131  *
132  * <tr><th>&nbsp;</th></tr>
133  * <tr align="left"><th colspan="2" id="classes">Character classes</th></tr>
134  *
135  * <tr><td valign="top" headers="construct classes">{@code [abc]}</td>
136  *     <td headers="matches">{@code a}, {@code b}, or {@code c} (simple class)</td></tr>
137  * <tr><td valign="top" headers="construct classes">{@code [^abc]}</td>
138  *     <td headers="matches">Any character except {@code a}, {@code b}, or {@code c} (negation)</td></tr>
139  * <tr><td valign="top" headers="construct classes">{@code [a-zA-Z]}</td>
140  *     <td headers="matches">{@code a} through {@code z}
141  *         or {@code A} through {@code Z}, inclusive (range)</td></tr>
142  * <tr><td valign="top" headers="construct classes">{@code [a-d[m-p]]}</td>
143  *     <td headers="matches">{@code a} through {@code d},
144  *      or {@code m} through {@code p}: {@code [a-dm-p]} (union)</td></tr>
145  * <tr><td valign="top" headers="construct classes">{@code [a-z&&[def]]}</td>
146  *     <td headers="matches">{@code d}, {@code e}, or {@code f} (intersection)</tr>
147  * <tr><td valign="top" headers="construct classes">{@code [a-z&&[^bc]]}</td>
148  *     <td headers="matches">{@code a} through {@code z},
149  *         except for {@code b} and {@code c}: {@code [ad-z]} (subtraction)</td></tr>
150  * <tr><td valign="top" headers="construct classes">{@code [a-z&&[^m-p]]}</td>
151  *     <td headers="matches">{@code a} through {@code z},
152  *          and not {@code m} through {@code p}: {@code [a-lq-z]}(subtraction)</td></tr>
153  * <tr><th>&nbsp;</th></tr>
154  *
155  * <tr align="left"><th colspan="2" id="predef">Predefined character classes</th></tr>
156  *
157  * <tr><td valign="top" headers="construct predef"><tt>.</tt></td>
158  *     <td headers="matches">Any character (may or may not match <a href="#lt">line terminators</a>)</td></tr>
159  * <tr><td valign="top" headers="construct predef"><tt>\d</tt></td>
160  *     <td headers="matches">A digit: <tt>[0-9]</tt></td></tr>
161  * <tr><td valign="top" headers="construct predef"><tt>\D</tt></td>
162  *     <td headers="matches">A non-digit: <tt>[^0-9]</tt></td></tr>
163  * <tr><td valign="top" headers="construct predef"><tt>\h</tt></td>
164  *     <td headers="matches">A horizontal whitespace character:
165  *     <tt>[ \t\xA0&#92;u1680&#92;u180e&#92;u2000-&#92;u200a&#92;u202f&#92;u205f&#92;u3000]</tt></td></tr>
166  * <tr><td valign="top" headers="construct predef"><tt>\H</tt></td>
167  *     <td headers="matches">A non-horizontal whitespace character: <tt>[^\h]</tt></td></tr>
168  * <tr><td valign="top" headers="construct predef"><tt>\s</tt></td>
169  *     <td headers="matches">A whitespace character: <tt>[ \t\n\x0B\f\r]</tt></td></tr>
170  * <tr><td valign="top" headers="construct predef"><tt>\S</tt></td>
171  *     <td headers="matches">A non-whitespace character: <tt>[^\s]</tt></td></tr>
172  * <tr><td valign="top" headers="construct predef"><tt>\v</tt></td>
173  *     <td headers="matches">A vertical whitespace character: <tt>[\n\x0B\f\r\x85&#92;u2028&#92;u2029]</tt>
174  *     </td></tr>
175  * <tr><td valign="top" headers="construct predef"><tt>\V</tt></td>
176  *     <td headers="matches">A non-vertical whitespace character: <tt>[^\v]</tt></td></tr>
177  * <tr><td valign="top" headers="construct predef"><tt>\w</tt></td>
178  *     <td headers="matches">A word character: <tt>[a-zA-Z_0-9]</tt></td></tr>
179  * <tr><td valign="top" headers="construct predef"><tt>\W</tt></td>
180  *     <td headers="matches">A non-word character: <tt>[^\w]</tt></td></tr>
181  * <tr><th>&nbsp;</th></tr>
182  * <tr align="left"><th colspan="2" id="posix"><b>POSIX character classes (US-ASCII only)</b></th></tr>
183  *
184  * <tr><td valign="top" headers="construct posix">{@code \p{Lower}}</td>
185  *     <td headers="matches">A lower-case alphabetic character: {@code [a-z]}</td></tr>
186  * <tr><td valign="top" headers="construct posix">{@code \p{Upper}}</td>
187  *     <td headers="matches">An upper-case alphabetic character:{@code [A-Z]}</td></tr>
188  * <tr><td valign="top" headers="construct posix">{@code \p{ASCII}}</td>
189  *     <td headers="matches">All ASCII:{@code [\x00-\x7F]}</td></tr>
190  * <tr><td valign="top" headers="construct posix">{@code \p{Alpha}}</td>
191  *     <td headers="matches">An alphabetic character:{@code [\p{Lower}\p{Upper}]}</td></tr>
192  * <tr><td valign="top" headers="construct posix">{@code \p{Digit}}</td>
193  *     <td headers="matches">A decimal digit: {@code [0-9]}</td></tr>
194  * <tr><td valign="top" headers="construct posix">{@code \p{Alnum}}</td>
195  *     <td headers="matches">An alphanumeric character:{@code [\p{Alpha}\p{Digit}]}</td></tr>
196  * <tr><td valign="top" headers="construct posix">{@code \p{Punct}}</td>
197  *     <td headers="matches">Punctuation: One of {@code !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~}</td></tr>
198  *     <!-- {@code [\!"#\$%&'\(\)\*\+,\-\./:;\<=\>\?@\[\\\]\^_`\{\|\}~]}
199  *          {@code [\X21-\X2F\X31-\X40\X5B-\X60\X7B-\X7E]} -->
200  * <tr><td valign="top" headers="construct posix">{@code \p{Graph}}</td>
201  *     <td headers="matches">A visible character: {@code [\p{Alnum}\p{Punct}]}</td></tr>
202  * <tr><td valign="top" headers="construct posix">{@code \p{Print}}</td>
203  *     <td headers="matches">A printable character: {@code [\p{Graph}\x20]}</td></tr>
204  * <tr><td valign="top" headers="construct posix">{@code \p{Blank}}</td>
205  *     <td headers="matches">A space or a tab: {@code [ \t]}</td></tr>
206  * <tr><td valign="top" headers="construct posix">{@code \p{Cntrl}}</td>
207  *     <td headers="matches">A control character: {@code [\x00-\x1F\x7F]}</td></tr>
208  * <tr><td valign="top" headers="construct posix">{@code \p{XDigit}}</td>
209  *     <td headers="matches">A hexadecimal digit: {@code [0-9a-fA-F]}</td></tr>
210  * <tr><td valign="top" headers="construct posix">{@code \p{Space}}</td>
211  *     <td headers="matches">A whitespace character: {@code [ \t\n\x0B\f\r]}</td></tr>
212  *
213  * <tr><th>&nbsp;</th></tr>
214  * <tr align="left"><th colspan="2">java.lang.Character classes (simple <a href="#jcc">java character type</a>)</th></tr>
215  *
216  * <tr><td valign="top"><tt>\p{javaLowerCase}</tt></td>
217  *     <td>Equivalent to java.lang.Character.isLowerCase()</td></tr>
218  * <tr><td valign="top"><tt>\p{javaUpperCase}</tt></td>
219  *     <td>Equivalent to java.lang.Character.isUpperCase()</td></tr>
220  * <tr><td valign="top"><tt>\p{javaWhitespace}</tt></td>
221  *     <td>Equivalent to java.lang.Character.isWhitespace()</td></tr>
222  * <tr><td valign="top"><tt>\p{javaMirrored}</tt></td>
223  *     <td>Equivalent to java.lang.Character.isMirrored()</td></tr>
224  *
225  * <tr><th>&nbsp;</th></tr>
226  * <tr align="left"><th colspan="2" id="unicode">Classes for Unicode scripts, blocks, categories and binary properties</th></tr>
227  * <tr><td valign="top" headers="construct unicode">{@code \p{IsLatin}}</td>
228  *     <td headers="matches">A Latin&nbsp;script character (<a href="#usc">script</a>)</td></tr>
229  * <tr><td valign="top" headers="construct unicode">{@code \p{InGreek}}</td>
230  *     <td headers="matches">A character in the Greek&nbsp;block (<a href="#ubc">block</a>)</td></tr>
231  * <tr><td valign="top" headers="construct unicode">{@code \p{Lu}}</td>
232  *     <td headers="matches">An uppercase letter (<a href="#ucc">category</a>)</td></tr>
233  * <tr><td valign="top" headers="construct unicode">{@code \p{IsAlphabetic}}</td>
234  *     <td headers="matches">An alphabetic character (<a href="#ubpc">binary property</a>)</td></tr>
235  * <tr><td valign="top" headers="construct unicode">{@code \p{Sc}}</td>
236  *     <td headers="matches">A currency symbol</td></tr>
237  * <tr><td valign="top" headers="construct unicode">{@code \P{InGreek}}</td>
238  *     <td headers="matches">Any character except one in the Greek block (negation)</td></tr>
239  * <tr><td valign="top" headers="construct unicode">{@code [\p{L}&&[^\p{Lu}]]}</td>
240  *     <td headers="matches">Any letter except an uppercase letter (subtraction)</td></tr>
241  *
242  * <tr><th>&nbsp;</th></tr>
243  * <tr align="left"><th colspan="2" id="bounds">Boundary matchers</th></tr>
244  *
245  * <tr><td valign="top" headers="construct bounds"><tt>^</tt></td>
246  *     <td headers="matches">The beginning of a line</td></tr>
247  * <tr><td valign="top" headers="construct bounds"><tt>$</tt></td>
248  *     <td headers="matches">The end of a line</td></tr>
249  * <tr><td valign="top" headers="construct bounds"><tt>\b</tt></td>
250  *     <td headers="matches">A word boundary</td></tr>
251  * <tr><td valign="top" headers="construct bounds"><tt>\B</tt></td>
252  *     <td headers="matches">A non-word boundary</td></tr>
253  * <tr><td valign="top" headers="construct bounds"><tt>\A</tt></td>
254  *     <td headers="matches">The beginning of the input</td></tr>
255  * <tr><td valign="top" headers="construct bounds"><tt>\G</tt></td>
256  *     <td headers="matches">The end of the previous match</td></tr>
257  * <tr><td valign="top" headers="construct bounds"><tt>\Z</tt></td>
258  *     <td headers="matches">The end of the input but for the final
259  *         <a href="#lt">terminator</a>, if&nbsp;any</td></tr>
260  * <tr><td valign="top" headers="construct bounds"><tt>\z</tt></td>
261  *     <td headers="matches">The end of the input</td></tr>
262  *
263  * <tr><th>&nbsp;</th></tr>
264  * <tr align="left"><th colspan="2" id="lineending">Linebreak matcher</th></tr>
265  * <tr><td valign="top" headers="construct lineending"><tt>\R</tt></td>
266  *     <td headers="matches">Any Unicode linebreak sequence, is equivalent to
267  *     <tt>&#92;u000D&#92;u000A|[&#92;u000A&#92;u000B&#92;u000C&#92;u000D&#92;u0085&#92;u2028&#92;u2029]
268  *     </tt></td></tr>
269  *
270  * <tr><th>&nbsp;</th></tr>
271  * <tr align="left"><th colspan="2" id="greedy">Greedy quantifiers</th></tr>
272  *
273  * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>?</tt></td>
274  *     <td headers="matches"><i>X</i>, once or not at all</td></tr>
275  * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>*</tt></td>
276  *     <td headers="matches"><i>X</i>, zero or more times</td></tr>
277  * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>+</tt></td>
278  *     <td headers="matches"><i>X</i>, one or more times</td></tr>
279  * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>{</tt><i>n</i><tt>}</tt></td>
280  *     <td headers="matches"><i>X</i>, exactly <i>n</i> times</td></tr>
281  * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>{</tt><i>n</i><tt>,}</tt></td>
282  *     <td headers="matches"><i>X</i>, at least <i>n</i> times</td></tr>
283  * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>{</tt><i>n</i><tt>,</tt><i>m</i><tt>}</tt></td>
284  *     <td headers="matches"><i>X</i>, at least <i>n</i> but not more than <i>m</i> times</td></tr>
285  *
286  * <tr><th>&nbsp;</th></tr>
287  * <tr align="left"><th colspan="2" id="reluc">Reluctant quantifiers</th></tr>
288  *
289  * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>??</tt></td>
290  *     <td headers="matches"><i>X</i>, once or not at all</td></tr>
291  * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>*?</tt></td>
292  *     <td headers="matches"><i>X</i>, zero or more times</td></tr>
293  * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>+?</tt></td>
294  *     <td headers="matches"><i>X</i>, one or more times</td></tr>
295  * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>{</tt><i>n</i><tt>}?</tt></td>
296  *     <td headers="matches"><i>X</i>, exactly <i>n</i> times</td></tr>
297  * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>{</tt><i>n</i><tt>,}?</tt></td>
298  *     <td headers="matches"><i>X</i>, at least <i>n</i> times</td></tr>
299  * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>{</tt><i>n</i><tt>,</tt><i>m</i><tt>}?</tt></td>
300  *     <td headers="matches"><i>X</i>, at least <i>n</i> but not more than <i>m</i> times</td></tr>
301  *
302  * <tr><th>&nbsp;</th></tr>
303  * <tr align="left"><th colspan="2" id="poss">Possessive quantifiers</th></tr>
304  *
305  * <tr><td valign="top" headers="construct poss"><i>X</i><tt>?+</tt></td>
306  *     <td headers="matches"><i>X</i>, once or not at all</td></tr>
307  * <tr><td valign="top" headers="construct poss"><i>X</i><tt>*+</tt></td>
308  *     <td headers="matches"><i>X</i>, zero or more times</td></tr>
309  * <tr><td valign="top" headers="construct poss"><i>X</i><tt>++</tt></td>
310  *     <td headers="matches"><i>X</i>, one or more times</td></tr>
311  * <tr><td valign="top" headers="construct poss"><i>X</i><tt>{</tt><i>n</i><tt>}+</tt></td>
312  *     <td headers="matches"><i>X</i>, exactly <i>n</i> times</td></tr>
313  * <tr><td valign="top" headers="construct poss"><i>X</i><tt>{</tt><i>n</i><tt>,}+</tt></td>
314  *     <td headers="matches"><i>X</i>, at least <i>n</i> times</td></tr>
315  * <tr><td valign="top" headers="construct poss"><i>X</i><tt>{</tt><i>n</i><tt>,</tt><i>m</i><tt>}+</tt></td>
316  *     <td headers="matches"><i>X</i>, at least <i>n</i> but not more than <i>m</i> times</td></tr>
317  *
318  * <tr><th>&nbsp;</th></tr>
319  * <tr align="left"><th colspan="2" id="logical">Logical operators</th></tr>
320  *
321  * <tr><td valign="top" headers="construct logical"><i>XY</i></td>
322  *     <td headers="matches"><i>X</i> followed by <i>Y</i></td></tr>
323  * <tr><td valign="top" headers="construct logical"><i>X</i><tt>|</tt><i>Y</i></td>
324  *     <td headers="matches">Either <i>X</i> or <i>Y</i></td></tr>
325  * <tr><td valign="top" headers="construct logical"><tt>(</tt><i>X</i><tt>)</tt></td>
326  *     <td headers="matches">X, as a <a href="#cg">capturing group</a></td></tr>
327  *
328  * <tr><th>&nbsp;</th></tr>
329  * <tr align="left"><th colspan="2" id="backref">Back references</th></tr>
330  *
331  * <tr><td valign="bottom" headers="construct backref"><tt>\</tt><i>n</i></td>
332  *     <td valign="bottom" headers="matches">Whatever the <i>n</i><sup>th</sup>
333  *     <a href="#cg">capturing group</a> matched</td></tr>
334  *
335  * <tr><td valign="bottom" headers="construct backref"><tt>\</tt><i>k</i>&lt;<i>name</i>&gt;</td>
336  *     <td valign="bottom" headers="matches">Whatever the
337  *     <a href="#groupname">named-capturing group</a> "name" matched. Only available for API 26 or above</td></tr>
338  *
339  * <tr><th>&nbsp;</th></tr>
340  * <tr align="left"><th colspan="2" id="quot">Quotation</th></tr>
341  *
342  * <tr><td valign="top" headers="construct quot"><tt>\</tt></td>
343  *     <td headers="matches">Nothing, but quotes the following character</td></tr>
344  * <tr><td valign="top" headers="construct quot"><tt>\Q</tt></td>
345  *     <td headers="matches">Nothing, but quotes all characters until <tt>\E</tt></td></tr>
346  * <tr><td valign="top" headers="construct quot"><tt>\E</tt></td>
347  *     <td headers="matches">Nothing, but ends quoting started by <tt>\Q</tt></td></tr>
348  *     <!-- Metachars: !$()*+.<>?[\]^{|} -->
349  *
350  * <tr><th>&nbsp;</th></tr>
351  * <tr align="left"><th colspan="2" id="special">Special constructs (named-capturing and non-capturing)</th></tr>
352  *
353  * <tr><td valign="top" headers="construct special"><tt>(?&lt;<a href="#groupname">name</a>&gt;</tt><i>X</i><tt>)</tt></td>
354  *     <td headers="matches"><i>X</i>, as a named-capturing group. Only available for API 26 or above.</td></tr>
355  * <tr><td valign="top" headers="construct special"><tt>(?:</tt><i>X</i><tt>)</tt></td>
356  *     <td headers="matches"><i>X</i>, as a non-capturing group</td></tr>
357  * <tr><td valign="top" headers="construct special"><tt>(?idmsuxU-idmsuxU)&nbsp;</tt></td>
358  *     <td headers="matches">Nothing, but turns match flags <a href="#CASE_INSENSITIVE">i</a>
359  * <a href="#UNIX_LINES">d</a> <a href="#MULTILINE">m</a> <a href="#DOTALL">s</a>
360  * <a href="#UNICODE_CASE">u</a> <a href="#COMMENTS">x</a> <a href="#UNICODE_CHARACTER_CLASS">U</a>
361  * on - off</td></tr>
362  * <tr><td valign="top" headers="construct special"><tt>(?idmsux-idmsux:</tt><i>X</i><tt>)</tt>&nbsp;&nbsp;</td>
363  *     <td headers="matches"><i>X</i>, as a <a href="#cg">non-capturing group</a> with the
364  *         given flags <a href="#CASE_INSENSITIVE">i</a> <a href="#UNIX_LINES">d</a>
365  * <a href="#MULTILINE">m</a> <a href="#DOTALL">s</a> <a href="#UNICODE_CASE">u</a >
366  * <a href="#COMMENTS">x</a> on - off</td></tr>
367  * <tr><td valign="top" headers="construct special"><tt>(?=</tt><i>X</i><tt>)</tt></td>
368  *     <td headers="matches"><i>X</i>, via zero-width positive lookahead</td></tr>
369  * <tr><td valign="top" headers="construct special"><tt>(?!</tt><i>X</i><tt>)</tt></td>
370  *     <td headers="matches"><i>X</i>, via zero-width negative lookahead</td></tr>
371  * <tr><td valign="top" headers="construct special"><tt>(?&lt;=</tt><i>X</i><tt>)</tt></td>
372  *     <td headers="matches"><i>X</i>, via zero-width positive lookbehind</td></tr>
373  * <tr><td valign="top" headers="construct special"><tt>(?&lt;!</tt><i>X</i><tt>)</tt></td>
374  *     <td headers="matches"><i>X</i>, via zero-width negative lookbehind</td></tr>
375  * <tr><td valign="top" headers="construct special"><tt>(?&gt;</tt><i>X</i><tt>)</tt></td>
376  *     <td headers="matches"><i>X</i>, as an independent, non-capturing group</td></tr>
377  *
378  * </table>
379  *
380  * <hr>
381  *
382  *
383  * <h3><a name="bs">Backslashes, escapes, and quoting</a></h3>
384  *
385  * <p> The backslash character (<tt>'\'</tt>) serves to introduce escaped
386  * constructs, as defined in the table above, as well as to quote characters
387  * that otherwise would be interpreted as unescaped constructs.  Thus the
388  * expression <tt>\\</tt> matches a single backslash and <tt>\{</tt> matches a
389  * left brace.
390  *
391  * <p> It is an error to use a backslash prior to any alphabetic character that
392  * does not denote an escaped construct; these are reserved for future
393  * extensions to the regular-expression language.  A backslash may be used
394  * prior to a non-alphabetic character regardless of whether that character is
395  * part of an unescaped construct.
396  *
397  * <p> Backslashes within string literals in Java source code are interpreted
398  * as required by
399  * <cite>The Java&trade; Language Specification</cite>
400  * as either Unicode escapes (section 3.3) or other character escapes (section 3.10.6)
401  * It is therefore necessary to double backslashes in string
402  * literals that represent regular expressions to protect them from
403  * interpretation by the Java bytecode compiler.  The string literal
404  * <tt>"&#92;b"</tt>, for example, matches a single backspace character when
405  * interpreted as a regular expression, while <tt>"&#92;&#92;b"</tt> matches a
406  * word boundary.  The string literal <tt>"&#92;(hello&#92;)"</tt> is illegal
407  * and leads to a compile-time error; in order to match the string
408  * <tt>(hello)</tt> the string literal <tt>"&#92;&#92;(hello&#92;&#92;)"</tt>
409  * must be used.
410  *
411  * <h3><a name="cc">Character Classes</a></h3>
412  *
413  *    <p> Character classes may appear within other character classes, and
414  *    may be composed by the union operator (implicit) and the intersection
415  *    operator (<tt>&amp;&amp;</tt>).
416  *    The union operator denotes a class that contains every character that is
417  *    in at least one of its operand classes.  The intersection operator
418  *    denotes a class that contains every character that is in both of its
419  *    operand classes.
420  *
421  *    <p> The precedence of character-class operators is as follows, from
422  *    highest to lowest:
423  *
424  *    <blockquote><table border="0" cellpadding="1" cellspacing="0"
425  *                 summary="Precedence of character class operators.">
426  *      <tr><th>1&nbsp;&nbsp;&nbsp;&nbsp;</th>
427  *        <td>Literal escape&nbsp;&nbsp;&nbsp;&nbsp;</td>
428  *        <td><tt>\x</tt></td></tr>
429  *     <tr><th>2&nbsp;&nbsp;&nbsp;&nbsp;</th>
430  *        <td>Grouping</td>
431  *        <td><tt>[...]</tt></td></tr>
432  *     <tr><th>3&nbsp;&nbsp;&nbsp;&nbsp;</th>
433  *        <td>Range</td>
434  *        <td><tt>a-z</tt></td></tr>
435  *      <tr><th>4&nbsp;&nbsp;&nbsp;&nbsp;</th>
436  *        <td>Union</td>
437  *        <td><tt>[a-e][i-u]</tt></td></tr>
438  *      <tr><th>5&nbsp;&nbsp;&nbsp;&nbsp;</th>
439  *        <td>Intersection</td>
440  *        <td>{@code [a-z&&[aeiou]]}</td></tr>
441  *    </table></blockquote>
442  *
443  *    <p> Note that a different set of metacharacters are in effect inside
444  *    a character class than outside a character class. For instance, the
445  *    regular expression <tt>.</tt> loses its special meaning inside a
446  *    character class, while the expression <tt>-</tt> becomes a range
447  *    forming metacharacter.
448  *
449  * <h3><a name="lt">Line terminators</a></h3>
450  *
451  * <p> A <i>line terminator</i> is a one- or two-character sequence that marks
452  * the end of a line of the input character sequence.  The following are
453  * recognized as line terminators:
454  *
455  * <ul>
456  *
457  *   <li> A newline (line feed) character&nbsp;(<tt>'\n'</tt>),
458  *
459  *   <li> A carriage-return character followed immediately by a newline
460  *   character&nbsp;(<tt>"\r\n"</tt>),
461  *
462  *   <li> A standalone carriage-return character&nbsp;(<tt>'\r'</tt>),
463  *
464  *   <li> A next-line character&nbsp;(<tt>'&#92;u0085'</tt>),
465  *
466  *   <li> A line-separator character&nbsp;(<tt>'&#92;u2028'</tt>), or
467  *
468  *   <li> A paragraph-separator character&nbsp;(<tt>'&#92;u2029</tt>).
469  *
470  * </ul>
471  * <p>If {@link #UNIX_LINES} mode is activated, then the only line terminators
472  * recognized are newline characters.
473  *
474  * <p> The regular expression <tt>.</tt> matches any character except a line
475  * terminator unless the {@link #DOTALL} flag is specified.
476  *
477  * <p> By default, the regular expressions <tt>^</tt> and <tt>$</tt> ignore
478  * line terminators and only match at the beginning and the end, respectively,
479  * of the entire input sequence. If {@link #MULTILINE} mode is activated then
480  * <tt>^</tt> matches at the beginning of input and after any line terminator
481  * except at the end of input. When in {@link #MULTILINE} mode <tt>$</tt>
482  * matches just before a line terminator or the end of the input sequence.
483  *
484  * <h3><a name="cg">Groups and capturing</a></h3>
485  *
486  * <h4><a name="gnumber">Group number</a></h4>
487  * <p> Capturing groups are numbered by counting their opening parentheses from
488  * left to right.  In the expression <tt>((A)(B(C)))</tt>, for example, there
489  * are four such groups: </p>
490  *
491  * <blockquote><table cellpadding=1 cellspacing=0 summary="Capturing group numberings">
492  * <tr><th>1&nbsp;&nbsp;&nbsp;&nbsp;</th>
493  *     <td><tt>((A)(B(C)))</tt></td></tr>
494  * <tr><th>2&nbsp;&nbsp;&nbsp;&nbsp;</th>
495  *     <td><tt>(A)</tt></td></tr>
496  * <tr><th>3&nbsp;&nbsp;&nbsp;&nbsp;</th>
497  *     <td><tt>(B(C))</tt></td></tr>
498  * <tr><th>4&nbsp;&nbsp;&nbsp;&nbsp;</th>
499  *     <td><tt>(C)</tt></td></tr>
500  * </table></blockquote>
501  *
502  * <p> Group zero always stands for the entire expression.
503  *
504  * <p> Capturing groups are so named because, during a match, each subsequence
505  * of the input sequence that matches such a group is saved.  The captured
506  * subsequence may be used later in the expression, via a back reference, and
507  * may also be retrieved from the matcher once the match operation is complete.
508  *
509  * <h4><a name="groupname">Group name</a></h4>
510  * <p>The constructs and APIs are available since API level 26. A capturing group
511  * can also be assigned a "name", a <tt>named-capturing group</tt>,
512  * and then be back-referenced later by the "name". Group names are composed of
513  * the following characters. The first character must be a <tt>letter</tt>.
514  *
515  * <ul>
516  *   <li> The uppercase letters <tt>'A'</tt> through <tt>'Z'</tt>
517  *        (<tt>'&#92;u0041'</tt>&nbsp;through&nbsp;<tt>'&#92;u005a'</tt>),
518  *   <li> The lowercase letters <tt>'a'</tt> through <tt>'z'</tt>
519  *        (<tt>'&#92;u0061'</tt>&nbsp;through&nbsp;<tt>'&#92;u007a'</tt>),
520  *   <li> The digits <tt>'0'</tt> through <tt>'9'</tt>
521  *        (<tt>'&#92;u0030'</tt>&nbsp;through&nbsp;<tt>'&#92;u0039'</tt>),
522  * </ul>
523  *
524  * <p> A <tt>named-capturing group</tt> is still numbered as described in
525  * <a href="#gnumber">Group number</a>.
526  *
527  * <p> The captured input associated with a group is always the subsequence
528  * that the group most recently matched.  If a group is evaluated a second time
529  * because of quantification then its previously-captured value, if any, will
530  * be retained if the second evaluation fails.  Matching the string
531  * <tt>"aba"</tt> against the expression <tt>(a(b)?)+</tt>, for example, leaves
532  * group two set to <tt>"b"</tt>.  All captured input is discarded at the
533  * beginning of each match.
534  *
535  * <p> Groups beginning with <tt>(?</tt> are either pure, <i>non-capturing</i> groups
536  * that do not capture text and do not count towards the group total, or
537  * <i>named-capturing</i> group.
538  *
539  * <h3> Unicode support </h3>
540  *
541  * <p> This class is in conformance with Level 1 of <a
542  * href="http://www.unicode.org/reports/tr18/"><i>Unicode Technical
543  * Standard #18: Unicode Regular Expression</i></a>, plus RL2.1
544  * Canonical Equivalents.
545  * <p>
546  * <b>Unicode escape sequences</b> such as <tt>&#92;u2014</tt> in Java source code
547  * are processed as described in section 3.3 of
548  * <cite>The Java&trade; Language Specification</cite>.
549  * Such escape sequences are also implemented directly by the regular-expression
550  * parser so that Unicode escapes can be used in expressions that are read from
551  * files or from the keyboard.  Thus the strings <tt>"&#92;u2014"</tt> and
552  * <tt>"\\u2014"</tt>, while not equal, compile into the same pattern, which
553  * matches the character with hexadecimal value <tt>0x2014</tt>.
554  * <p>
555  * A Unicode character can also be represented in a regular-expression by
556  * using its <b>Hex notation</b>(hexadecimal code point value) directly as described in construct
557  * <tt>&#92;x{...}</tt>, for example a supplementary character U+2011F
558  * can be specified as <tt>&#92;x{2011F}</tt>, instead of two consecutive
559  * Unicode escape sequences of the surrogate pair
560  * <tt>&#92;uD840</tt><tt>&#92;uDD1F</tt>.
561  * <p>
562  * Unicode scripts, blocks, categories and binary properties are written with
563  * the <tt>\p</tt> and <tt>\P</tt> constructs as in Perl.
564  * <tt>\p{</tt><i>prop</i><tt>}</tt> matches if
565  * the input has the property <i>prop</i>, while <tt>\P{</tt><i>prop</i><tt>}</tt>
566  * does not match if the input has that property.
567  * <p>
568  * Scripts, blocks, categories and binary properties can be used both inside
569  * and outside of a character class.
570  *
571  * <p>
572  * <b><a name="usc">Scripts</a></b> are specified either with the prefix {@code Is}, as in
573  * {@code IsHiragana}, or by using  the {@code script} keyword (or its short
574  * form {@code sc})as in {@code script=Hiragana} or {@code sc=Hiragana}.
575  * <p>
576  * The script names supported by <code>Pattern</code> are the valid script names
577  * accepted and defined by
578  * {@link java.lang.Character.UnicodeScript#forName(String) UnicodeScript.forName}.
579  *
580  * <p>
581  * <b><a name="ubc">Blocks</a></b> are specified with the prefix {@code In}, as in
582  * {@code InMongolian}, or by using the keyword {@code block} (or its short
583  * form {@code blk}) as in {@code block=Mongolian} or {@code blk=Mongolian}.
584  * <p>
585  * The block names supported by <code>Pattern</code> are the valid block names
586  * accepted and defined by
587  * {@link java.lang.Character.UnicodeBlock#forName(String) UnicodeBlock.forName}.
588  * <p>
589  *
590  * <b><a name="ucc">Categories</a></b> may be specified with the optional prefix {@code Is}:
591  * Both {@code \p{L}} and {@code \p{IsL}} denote the category of Unicode
592  * letters. Same as scripts and blocks, categories can also be specified
593  * by using the keyword {@code general_category} (or its short form
594  * {@code gc}) as in {@code general_category=Lu} or {@code gc=Lu}.
595  * <p>
596  * The supported categories are those of
597  * <a href="http://www.unicode.org/unicode/standard/standard.html">
598  * <i>The Unicode Standard</i></a> in the version specified by the
599  * {@link java.lang.Character Character} class. The category names are those
600  * defined in the Standard, both normative and informative.
601  * <p>
602  *
603  * <b><a name="ubpc">Binary properties</a></b> are specified with the prefix {@code Is}, as in
604  * {@code IsAlphabetic}. The supported binary properties by <code>Pattern</code>
605  * are
606  * <ul>
607  *   <li> Alphabetic
608  *   <li> Ideographic
609  *   <li> Letter
610  *   <li> Lowercase
611  *   <li> Uppercase
612  *   <li> Titlecase
613  *   <li> Punctuation
614  *   <Li> Control
615  *   <li> White_Space
616  *   <li> Digit
617  *   <li> Hex_Digit
618  *   <li> Join_Control
619  *   <li> Noncharacter_Code_Point
620  *   <li> Assigned
621  * </ul>
622  * <p>
623  * The following <b>Predefined Character classes</b> and <b>POSIX character classes</b>
624  * are in conformance with the recommendation of <i>Annex C: Compatibility Properties</i>
625  * of <a href="http://www.unicode.org/reports/tr18/"><i>Unicode Regular Expression
626  * </i></a>.
627  *
628  * <table border="0" cellpadding="1" cellspacing="0"
629  *  summary="predefined and posix character classes in Unicode mode">
630  * <tr align="left">
631  * <th align="left" id="predef_classes">Classes</th>
632  * <th align="left" id="predef_matches">Matches</th>
633  *</tr>
634  * <tr><td><tt>\p{Lower}</tt></td>
635  *     <td>A lowercase character:<tt>\p{IsLowercase}</tt></td></tr>
636  * <tr><td><tt>\p{Upper}</tt></td>
637  *     <td>An uppercase character:<tt>\p{IsUppercase}</tt></td></tr>
638  * <tr><td><tt>\p{ASCII}</tt></td>
639  *     <td>All ASCII:<tt>[\x00-\x7F]</tt></td></tr>
640  * <tr><td><tt>\p{Alpha}</tt></td>
641  *     <td>An alphabetic character:<tt>\p{IsAlphabetic}</tt></td></tr>
642  * <tr><td><tt>\p{Digit}</tt></td>
643  *     <td>A decimal digit character:<tt>p{IsDigit}</tt></td></tr>
644  * <tr><td><tt>\p{Alnum}</tt></td>
645  *     <td>An alphanumeric character:<tt>[\p{IsAlphabetic}\p{IsDigit}]</tt></td></tr>
646  * <tr><td><tt>\p{Punct}</tt></td>
647  *     <td>A punctuation character:<tt>p{IsPunctuation}</tt></td></tr>
648  * <tr><td><tt>\p{Graph}</tt></td>
649  *     <td>A visible character: <tt>[^\p{IsWhite_Space}\p{gc=Cc}\p{gc=Cs}\p{gc=Cn}]</tt></td></tr>
650  * <tr><td><tt>\p{Print}</tt></td>
651  *     <td>A printable character: {@code [\p{Graph}\p{Blank}&&[^\p{Cntrl}]]}</td></tr>
652  * <tr><td><tt>\p{Blank}</tt></td>
653  *     <td>A space or a tab: {@code [\p{IsWhite_Space}&&[^\p{gc=Zl}\p{gc=Zp}\x0a\x0b\x0c\x0d\x85]]}</td></tr>
654  * <tr><td><tt>\p{Cntrl}</tt></td>
655  *     <td>A control character: <tt>\p{gc=Cc}</tt></td></tr>
656  * <tr><td><tt>\p{XDigit}</tt></td>
657  *     <td>A hexadecimal digit: <tt>[\p{gc=Nd}\p{IsHex_Digit}]</tt></td></tr>
658  * <tr><td><tt>\p{Space}</tt></td>
659  *     <td>A whitespace character:<tt>\p{IsWhite_Space}</tt></td></tr>
660  * <tr><td><tt>\d</tt></td>
661  *     <td>A digit: <tt>\p{IsDigit}</tt></td></tr>
662  * <tr><td><tt>\D</tt></td>
663  *     <td>A non-digit: <tt>[^\d]</tt></td></tr>
664  * <tr><td><tt>\s</tt></td>
665  *     <td>A whitespace character: <tt>\p{IsWhite_Space}</tt></td></tr>
666  * <tr><td><tt>\S</tt></td>
667  *     <td>A non-whitespace character: <tt>[^\s]</tt></td></tr>
668  * <tr><td><tt>\w</tt></td>
669  *     <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>
670  * <tr><td><tt>\W</tt></td>
671  *     <td>A non-word character: <tt>[^\w]</tt></td></tr>
672  * </table>
673  * <p>
674  * <a name="jcc">
675  * Categories that behave like the java.lang.Character
676  * boolean is<i>methodname</i> methods (except for the deprecated ones) are
677  * available through the same <tt>\p{</tt><i>prop</i><tt>}</tt> syntax where
678  * the specified property has the name <tt>java<i>methodname</i></tt></a>.
679  *
680  * <h3> Comparison to Perl 5 </h3>
681  *
682  * <p>The <code>Pattern</code> engine performs traditional NFA-based matching
683  * with ordered alternation as occurs in Perl 5.
684  *
685  * <p> Perl constructs not supported by this class: </p>
686  *
687  * <ul>
688  *    <li><p> Predefined character classes (Unicode character)
689  *    <p><tt>\X&nbsp;&nbsp;&nbsp;&nbsp;</tt>Match Unicode
690  *    <a href="http://www.unicode.org/reports/tr18/#Default_Grapheme_Clusters">
691  *    <i>extended grapheme cluster</i></a>
692  *    </p></li>
693  *
694  *    <li><p> The backreference constructs, <tt>\g{</tt><i>n</i><tt>}</tt> for
695  *    the <i>n</i><sup>th</sup><a href="#cg">capturing group</a> and
696  *    <tt>\g{</tt><i>name</i><tt>}</tt> for
697  *    <a href="#groupname">named-capturing group</a>.
698  *    </p></li>
699  *
700  *    <li><p> The named character construct, <tt>\N{</tt><i>name</i><tt>}</tt>
701  *    for a Unicode character by its name.
702  *    </p></li>
703  *
704  *    <li><p> The conditional constructs
705  *    <tt>(?(</tt><i>condition</i><tt>)</tt><i>X</i><tt>)</tt> and
706  *    <tt>(?(</tt><i>condition</i><tt>)</tt><i>X</i><tt>|</tt><i>Y</i><tt>)</tt>,
707  *    </p></li>
708  *
709  *    <li><p> The embedded code constructs <tt>(?{</tt><i>code</i><tt>})</tt>
710  *    and <tt>(??{</tt><i>code</i><tt>})</tt>,</p></li>
711  *
712  *    <li><p> The embedded comment syntax <tt>(?#comment)</tt>, and </p></li>
713  *
714  *    <li><p> The preprocessing operations <tt>\l</tt> <tt>&#92;u</tt>,
715  *    <tt>\L</tt>, and <tt>\U</tt>.  </p></li>
716  *
717  * </ul>
718  *
719  * <p> Constructs supported by this class but not by Perl: </p>
720  *
721  * <ul>
722  *
723  *    <li><p> Character-class union and intersection as described
724  *    <a href="#cc">above</a>.</p></li>
725  *
726  * </ul>
727  *
728  * <p> Notable differences from Perl: </p>
729  *
730  * <ul>
731  *
732  *    <li><p> In Perl, <tt>\1</tt> through <tt>\9</tt> are always interpreted
733  *    as back references; a backslash-escaped number greater than <tt>9</tt> is
734  *    treated as a back reference if at least that many subexpressions exist,
735  *    otherwise it is interpreted, if possible, as an octal escape.  In this
736  *    class octal escapes must always begin with a zero. In this class,
737  *    <tt>\1</tt> through <tt>\9</tt> are always interpreted as back
738  *    references, and a larger number is accepted as a back reference if at
739  *    least that many subexpressions exist at that point in the regular
740  *    expression, otherwise the parser will drop digits until the number is
741  *    smaller or equal to the existing number of groups or it is one digit.
742  *    </p></li>
743  *
744  *    <li><p> Perl uses the <tt>g</tt> flag to request a match that resumes
745  *    where the last match left off.  This functionality is provided implicitly
746  *    by the {@link Matcher} class: Repeated invocations of the {@link
747  *    Matcher#find find} method will resume where the last match left off,
748  *    unless the matcher is reset.  </p></li>
749  *
750  *    <li><p> In Perl, embedded flags at the top level of an expression affect
751  *    the whole expression.  In this class, embedded flags always take effect
752  *    at the point at which they appear, whether they are at the top level or
753  *    within a group; in the latter case, flags are restored at the end of the
754  *    group just as in Perl.  </p></li>
755  *
756  * </ul>
757  *
758  *
759  * <p> For a more precise description of the behavior of regular expression
760  * constructs, please see <a href="http://www.oreilly.com/catalog/regex3/">
761  * <i>Mastering Regular Expressions, 3nd Edition</i>, Jeffrey E. F. Friedl,
762  * O'Reilly and Associates, 2006.</a>
763  * </p>
764  *
765  * @see java.lang.String#split(String, int)
766  * @see java.lang.String#split(String)
767  *
768  * @author      Mike McCloskey
769  * @author      Mark Reinhold
770  * @author      JSR-51 Expert Group
771  * @since       1.4
772  * @spec        JSR-51
773  */
774 
775 public final class Pattern
776     implements java.io.Serializable
777 {
778 
779     /**
780      * Regular expression modifier values.  Instead of being passed as
781      * arguments, they can also be passed as inline modifiers.
782      * For example, the following statements have the same effect.
783      * <pre>
784      * RegExp r1 = RegExp.compile("abc", Pattern.I|Pattern.M);
785      * RegExp r2 = RegExp.compile("(?im)abc", 0);
786      * </pre>
787      *
788      * The flags are duplicated so that the familiar Perl match flag
789      * names are available.
790      */
791 
792     /**
793      * Enables Unix lines mode.
794      *
795      * <p> In this mode, only the <tt>'\n'</tt> line terminator is recognized
796      * in the behavior of <tt>.</tt>, <tt>^</tt>, and <tt>$</tt>.
797      *
798      * <p> Unix lines mode can also be enabled via the embedded flag
799      * expression&nbsp;<tt>(?d)</tt>.
800      */
801     public static final int UNIX_LINES = 0x01;
802 
803     /**
804      * Enables case-insensitive matching.
805      *
806      * <p> By default, case-insensitive matching assumes that only characters
807      * in the US-ASCII charset are being matched.  Unicode-aware
808      * case-insensitive matching can be enabled by specifying the {@link
809      * #UNICODE_CASE} flag in conjunction with this flag.
810      *
811      * <p> Case-insensitive matching can also be enabled via the embedded flag
812      * expression&nbsp;<tt>(?i)</tt>.
813      *
814      * <p> Specifying this flag may impose a slight performance penalty.  </p>
815      */
816     public static final int CASE_INSENSITIVE = 0x02;
817 
818     /**
819      * Permits whitespace and comments in pattern.
820      *
821      * <p> In this mode, whitespace is ignored, and embedded comments starting
822      * with <tt>#</tt> are ignored until the end of a line.
823      *
824      * <p> Comments mode can also be enabled via the embedded flag
825      * expression&nbsp;<tt>(?x)</tt>.
826      */
827     public static final int COMMENTS = 0x04;
828 
829     /**
830      * Enables multiline mode.
831      *
832      * <p> In multiline mode the expressions <tt>^</tt> and <tt>$</tt> match
833      * just after or just before, respectively, a line terminator or the end of
834      * the input sequence.  By default these expressions only match at the
835      * beginning and the end of the entire input sequence.
836      *
837      * <p> Multiline mode can also be enabled via the embedded flag
838      * expression&nbsp;<tt>(?m)</tt>.  </p>
839      */
840     public static final int MULTILINE = 0x08;
841 
842     /**
843      * Enables literal parsing of the pattern.
844      *
845      * <p> When this flag is specified then the input string that specifies
846      * the pattern is treated as a sequence of literal characters.
847      * Metacharacters or escape sequences in the input sequence will be
848      * given no special meaning.
849      *
850      * <p>The flags CASE_INSENSITIVE and UNICODE_CASE retain their impact on
851      * matching when used in conjunction with this flag. The other flags
852      * become superfluous.
853      *
854      * <p> There is no embedded flag character for enabling literal parsing.
855      * @since 1.5
856      */
857     public static final int LITERAL = 0x10;
858 
859     /**
860      * Enables dotall mode.
861      *
862      * <p> In dotall mode, the expression <tt>.</tt> matches any character,
863      * including a line terminator.  By default this expression does not match
864      * line terminators.
865      *
866      * <p> Dotall mode can also be enabled via the embedded flag
867      * expression&nbsp;<tt>(?s)</tt>.  (The <tt>s</tt> is a mnemonic for
868      * "single-line" mode, which is what this is called in Perl.)  </p>
869      */
870     public static final int DOTALL = 0x20;
871 
872     /**
873      * Enables Unicode-aware case folding.
874      *
875      * <p> When this flag is specified then case-insensitive matching, when
876      * enabled by the {@link #CASE_INSENSITIVE} flag, is done in a manner
877      * consistent with the Unicode Standard.  By default, case-insensitive
878      * matching assumes that only characters in the US-ASCII charset are being
879      * matched.
880      *
881      * <p> Unicode-aware case folding can also be enabled via the embedded flag
882      * expression&nbsp;<tt>(?u)</tt>.
883      *
884      * <p> Specifying this flag may impose a performance penalty.  </p>
885      */
886     public static final int UNICODE_CASE = 0x40;
887 
888     /**
889      * Enables canonical equivalence.
890      *
891      * <p> When this flag is specified then two characters will be considered
892      * to match if, and only if, their full canonical decompositions match.
893      * The expression <tt>"a&#92;u030A"</tt>, for example, will match the
894      * string <tt>"&#92;u00E5"</tt> when this flag is specified.  By default,
895      * matching does not take canonical equivalence into account.
896      *
897      * <p> There is no embedded flag character for enabling canonical
898      * equivalence.
899      *
900      * <p> Specifying this flag may impose a performance penalty.  </p>
901      */
902     public static final int CANON_EQ = 0x80;
903 
904     // Android-changed: Android always uses unicode character classes.
905     /**
906      * Enables the Unicode version of <i>Predefined character classes</i> and
907      * <i>POSIX character classes</i> as defined by <a href="http://www.unicode.org/reports/tr18/"><i>Unicode Technical
908      * Standard #18: Unicode Regular Expression</i></a>
909      * <i>Annex C: Compatibility Properties</i>.
910      * <p>
911      *
912      * This flag has no effect on Android, unicode character classes are always
913      * used.
914      *
915      * @since 1.7
916      */
917     public static final int UNICODE_CHARACTER_CLASS = 0x100;
918 
919     /* Pattern has only two serialized components: The pattern string
920      * and the flags, which are all that is needed to recompile the pattern
921      * when it is deserialized.
922      */
923 
924     /** use serialVersionUID from Merlin b59 for interoperability */
925     private static final long serialVersionUID = 5073258162644648461L;
926 
927     /**
928      * The original regular-expression pattern string.
929      *
930      * @serial
931      */
932     // Android-changed: reimplement matching logic natively via ICU.
933     // private String pattern;
934     private final String pattern;
935 
936     /**
937      * The original pattern flags.
938      *
939      * @serial
940      */
941     // Android-changed: reimplement matching logic natively via ICU.
942     // private int flags;
943     private final int flags;
944 
945     // BEGIN Android-changed: reimplement matching logic natively via ICU.
946     // We only need some tie-ins to native memory, instead of a large number
947     // of fields on the .java side.
948     @ReachabilitySensitive
949     transient long address;
950 
951     private static final NativeAllocationRegistry registry =
952             NativeAllocationRegistry.createMalloced(Pattern.class.getClassLoader(),
953             getNativeFinalizer());
954     // END Android-changed: reimplement matching logic natively via ICU.
955 
956     /**
957      * Compiles the given regular expression into a pattern.
958      *
959      * @param  regex
960      *         The expression to be compiled
961      * @return the given regular expression compiled into a pattern
962      * @throws  PatternSyntaxException
963      *          If the expression's syntax is invalid
964      */
compile(String regex)965     public static Pattern compile(String regex) {
966         return new Pattern(regex, 0);
967     }
968 
969     /**
970      * Compiles the given regular expression into a pattern with the given
971      * flags.
972      *
973      * @param  regex
974      *         The expression to be compiled
975      *
976      * @param  flags
977      *         Match flags, a bit mask that may include
978      *         {@link #CASE_INSENSITIVE}, {@link #MULTILINE}, {@link #DOTALL},
979      *         {@link #UNICODE_CASE}, {@link #CANON_EQ}, {@link #UNIX_LINES},
980      *         {@link #LITERAL}, {@link #UNICODE_CHARACTER_CLASS}
981      *         and {@link #COMMENTS}
982      *
983      * @return the given regular expression compiled into a pattern with the given flags
984      * @throws  IllegalArgumentException
985      *          If bit values other than those corresponding to the defined
986      *          match flags are set in <tt>flags</tt>
987      *
988      * @throws  PatternSyntaxException
989      *          If the expression's syntax is invalid
990      */
compile(String regex, int flags)991     public static Pattern compile(String regex, int flags) {
992         return new Pattern(regex, flags);
993     }
994 
995     /**
996      * Returns the regular expression from which this pattern was compiled.
997      *
998      * @return  The source of this pattern
999      */
pattern()1000     public String pattern() {
1001         return pattern;
1002     }
1003 
1004     /**
1005      * <p>Returns the string representation of this pattern. This
1006      * is the regular expression from which this pattern was
1007      * compiled.</p>
1008      *
1009      * @return  The string representation of this pattern
1010      * @since 1.5
1011      */
toString()1012     public String toString() {
1013         return pattern;
1014     }
1015 
1016     /**
1017      * Creates a matcher that will match the given input against this pattern.
1018      *
1019      * @param  input
1020      *         The character sequence to be matched
1021      *
1022      * @return  A new matcher for this pattern
1023      */
matcher(CharSequence input)1024     public Matcher matcher(CharSequence input) {
1025         // Android-removed: Pattern is eagerly compiled() upon construction.
1026         /*
1027         if (!compiled) {
1028             synchronized(this) {
1029                 if (!compiled)
1030                     compile();
1031             }
1032         }
1033         */
1034         Matcher m = new Matcher(this, input);
1035         return m;
1036     }
1037 
1038     /**
1039      * Returns this pattern's match flags.
1040      *
1041      * @return  The match flags specified when this pattern was compiled
1042      */
flags()1043     public int flags() {
1044         return flags;
1045     }
1046 
1047     /**
1048      * Compiles the given regular expression and attempts to match the given
1049      * input against it.
1050      *
1051      * <p> An invocation of this convenience method of the form
1052      *
1053      * <blockquote><pre>
1054      * Pattern.matches(regex, input);</pre></blockquote>
1055      *
1056      * behaves in exactly the same way as the expression
1057      *
1058      * <blockquote><pre>
1059      * Pattern.compile(regex).matcher(input).matches()</pre></blockquote>
1060      *
1061      * <p> If a pattern is to be used multiple times, compiling it once and reusing
1062      * it will be more efficient than invoking this method each time.  </p>
1063      *
1064      * @param  regex
1065      *         The expression to be compiled
1066      *
1067      * @param  input
1068      *         The character sequence to be matched
1069      * @return whether or not the regular expression matches on the input
1070      * @throws  PatternSyntaxException
1071      *          If the expression's syntax is invalid
1072      */
matches(String regex, CharSequence input)1073     public static boolean matches(String regex, CharSequence input) {
1074         Pattern p = Pattern.compile(regex);
1075         Matcher m = p.matcher(input);
1076         return m.matches();
1077     }
1078 
1079     // Android-changed: Adopt split() behavior change only for apps targeting API > 28.
1080     // http://b/109659282#comment7
1081     /**
1082      * Splits the given input sequence around matches of this pattern.
1083      *
1084      * <p> The array returned by this method contains each substring of the
1085      * input sequence that is terminated by another subsequence that matches
1086      * this pattern or is terminated by the end of the input sequence.  The
1087      * substrings in the array are in the order in which they occur in the
1088      * input. If this pattern does not match any subsequence of the input then
1089      * the resulting array has just one element, namely the input sequence in
1090      * string form.
1091      *
1092      * <p> When there is a positive-width match at the beginning of the input
1093      * sequence then an empty leading substring is included at the beginning
1094      * of the resulting array. A zero-width match at the beginning however
1095      * can only produce such an empty leading substring for apps running on or
1096      * targeting API versions <= 28.
1097      *
1098      * <p> The <tt>limit</tt> parameter controls the number of times the
1099      * pattern is applied and therefore affects the length of the resulting
1100      * array.  If the limit <i>n</i> is greater than zero then the pattern
1101      * will be applied at most <i>n</i>&nbsp;-&nbsp;1 times, the array's
1102      * length will be no greater than <i>n</i>, and the array's last entry
1103      * will contain all input beyond the last matched delimiter.  If <i>n</i>
1104      * is non-positive then the pattern will be applied as many times as
1105      * possible and the array can have any length.  If <i>n</i> is zero then
1106      * the pattern will be applied as many times as possible, the array can
1107      * have any length, and trailing empty strings will be discarded.
1108      *
1109      * <p> The input <tt>"boo:and:foo"</tt>, for example, yields the following
1110      * results with these parameters:
1111      *
1112      * <blockquote><table cellpadding=1 cellspacing=0
1113      *              summary="Split examples showing regex, limit, and result">
1114      * <tr><th align="left"><i>Regex&nbsp;&nbsp;&nbsp;&nbsp;</i></th>
1115      *     <th align="left"><i>Limit&nbsp;&nbsp;&nbsp;&nbsp;</i></th>
1116      *     <th align="left"><i>Result&nbsp;&nbsp;&nbsp;&nbsp;</i></th></tr>
1117      * <tr><td align=center>:</td>
1118      *     <td align=center>2</td>
1119      *     <td><tt>{ "boo", "and:foo" }</tt></td></tr>
1120      * <tr><td align=center>:</td>
1121      *     <td align=center>5</td>
1122      *     <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
1123      * <tr><td align=center>:</td>
1124      *     <td align=center>-2</td>
1125      *     <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
1126      * <tr><td align=center>o</td>
1127      *     <td align=center>5</td>
1128      *     <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
1129      * <tr><td align=center>o</td>
1130      *     <td align=center>-2</td>
1131      *     <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
1132      * <tr><td align=center>o</td>
1133      *     <td align=center>0</td>
1134      *     <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
1135      * </table></blockquote>
1136      *
1137      * @param  input
1138      *         The character sequence to be split
1139      *
1140      * @param  limit
1141      *         The result threshold, as described above
1142      *
1143      * @return  The array of strings computed by splitting the input
1144      *          around matches of this pattern
1145      */
split(CharSequence input, int limit)1146     public String[] split(CharSequence input, int limit) {
1147         // BEGIN Android-added: fastSplit() to speed up simple cases.
1148         String[] fast = fastSplit(pattern, input.toString(), limit);
1149         if (fast != null) {
1150             return fast;
1151         }
1152         // END Android-added: fastSplit() to speed up simple cases.
1153         int index = 0;
1154         boolean matchLimited = limit > 0;
1155         ArrayList<String> matchList = new ArrayList<>();
1156         Matcher m = matcher(input);
1157 
1158         // Add segments before each match found
1159         while(m.find()) {
1160             if (!matchLimited || matchList.size() < limit - 1) {
1161                 if (index == 0 && index == m.start() && m.start() == m.end()) {
1162                     // no empty leading substring included for zero-width match
1163                     // at the beginning of the input char sequence.
1164                     // BEGIN Android-changed: split() compat behavior for apps targeting <= 28.
1165                     // continue;
1166                     int targetSdkVersion = VMRuntime.getRuntime().getTargetSdkVersion();
1167                     if (targetSdkVersion > 28) {
1168                         continue;
1169                     }
1170                     // END Android-changed: split() compat behavior for apps targeting <= 28.
1171                 }
1172                 String match = input.subSequence(index, m.start()).toString();
1173                 matchList.add(match);
1174                 index = m.end();
1175             } else if (matchList.size() == limit - 1) { // last one
1176                 String match = input.subSequence(index,
1177                                                  input.length()).toString();
1178                 matchList.add(match);
1179                 index = m.end();
1180             }
1181         }
1182 
1183         // If no match was found, return this
1184         if (index == 0)
1185             return new String[] {input.toString()};
1186 
1187         // Add remaining segment
1188         if (!matchLimited || matchList.size() < limit)
1189             matchList.add(input.subSequence(index, input.length()).toString());
1190 
1191         // Construct result
1192         int resultSize = matchList.size();
1193         if (limit == 0)
1194             while (resultSize > 0 && matchList.get(resultSize-1).equals(""))
1195                 resultSize--;
1196         String[] result = new String[resultSize];
1197         return matchList.subList(0, resultSize).toArray(result);
1198     }
1199 
1200     // BEGIN Android-added: fastSplit() to speed up simple cases.
1201     private static final String FASTSPLIT_METACHARACTERS = "\\?*+[](){}^$.|";
1202 
1203     /**
1204      * Returns a result equivalent to {@code s.split(separator, limit)} if it's able
1205      * to compute it more cheaply than native impl, or null if the caller should fall back to
1206      * using native impl.
1207      *
1208      *  fastpath will work  if the regex is a
1209      *   (1)one-char String and this character is not one of the
1210      *      RegEx's meta characters ".$|()[{^?*+\\", or
1211      *   (2)two-char String and the first char is the backslash and
1212      *      the second is one of regEx's meta characters ".$|()[{^?*+\\".
1213      * @hide
1214      */
fastSplit(String re, String input, int limit)1215     public static String[] fastSplit(String re, String input, int limit) {
1216         // Can we do it cheaply?
1217         int len = re.length();
1218         if (len == 0) {
1219             return null;
1220         }
1221         char ch = re.charAt(0);
1222         if (len == 1 && FASTSPLIT_METACHARACTERS.indexOf(ch) == -1) {
1223             // We're looking for a single non-metacharacter. Easy.
1224         } else if (len == 2 && ch == '\\') {
1225             // We're looking for a quoted character.
1226             // Quoted metacharacters are effectively single non-metacharacters.
1227             ch = re.charAt(1);
1228             if (FASTSPLIT_METACHARACTERS.indexOf(ch) == -1) {
1229                 return null;
1230             }
1231         } else {
1232             return null;
1233         }
1234 
1235         // We can do this cheaply...
1236 
1237         // Unlike Perl, which considers the result of splitting the empty string to be the empty
1238         // array, Java returns an array containing the empty string.
1239         if (input.isEmpty()) {
1240             return new String[] { "" };
1241         }
1242 
1243         // Count separators
1244         int separatorCount = 0;
1245         int begin = 0;
1246         int end;
1247         while (separatorCount + 1 != limit && (end = input.indexOf(ch, begin)) != -1) {
1248             ++separatorCount;
1249             begin = end + 1;
1250         }
1251         int lastPartEnd = input.length();
1252         if (limit == 0 && begin == lastPartEnd) {
1253             // Last part is empty for limit == 0, remove all trailing empty matches.
1254             if (separatorCount == lastPartEnd) {
1255                 // Input contains only separators.
1256                 return EmptyArray.STRING;
1257             }
1258             // Find the beginning of trailing separators.
1259             do {
1260                 --begin;
1261             } while (input.charAt(begin - 1) == ch);
1262             // Reduce separatorCount and fix lastPartEnd.
1263             separatorCount -= input.length() - begin;
1264             lastPartEnd = begin;
1265         }
1266 
1267         // Collect the result parts.
1268         String[] result = new String[separatorCount + 1];
1269         begin = 0;
1270         for (int i = 0; i != separatorCount; ++i) {
1271             end = input.indexOf(ch, begin);
1272             result[i] = input.substring(begin, end);
1273             begin = end + 1;
1274         }
1275         // Add last part.
1276         result[separatorCount] = input.substring(begin, lastPartEnd);
1277         return result;
1278     }
1279     // END Android-added: fastSplit() to speed up simple cases.
1280 
1281     /**
1282      * Splits the given input sequence around matches of this pattern.
1283      *
1284      * <p> This method works as if by invoking the two-argument {@link
1285      * #split(java.lang.CharSequence, int) split} method with the given input
1286      * sequence and a limit argument of zero.  Trailing empty strings are
1287      * therefore not included in the resulting array. </p>
1288      *
1289      * <p> The input <tt>"boo:and:foo"</tt>, for example, yields the following
1290      * results with these expressions:
1291      *
1292      * <blockquote><table cellpadding=1 cellspacing=0
1293      *              summary="Split examples showing regex and result">
1294      * <tr><th align="left"><i>Regex&nbsp;&nbsp;&nbsp;&nbsp;</i></th>
1295      *     <th align="left"><i>Result</i></th></tr>
1296      * <tr><td align=center>:</td>
1297      *     <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
1298      * <tr><td align=center>o</td>
1299      *     <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
1300      * </table></blockquote>
1301      *
1302      *
1303      * @param  input
1304      *         The character sequence to be split
1305      *
1306      * @return  The array of strings computed by splitting the input
1307      *          around matches of this pattern
1308      */
split(CharSequence input)1309     public String[] split(CharSequence input) {
1310         return split(input, 0);
1311     }
1312 
1313     /**
1314      * Returns a literal pattern <code>String</code> for the specified
1315      * <code>String</code>.
1316      *
1317      * <p>This method produces a <code>String</code> that can be used to
1318      * create a <code>Pattern</code> that would match the string
1319      * <code>s</code> as if it were a literal pattern.</p> Metacharacters
1320      * or escape sequences in the input sequence will be given no special
1321      * meaning.
1322      *
1323      * @param  s The string to be literalized
1324      * @return  A literal string replacement
1325      * @since 1.5
1326      */
quote(String s)1327     public static String quote(String s) {
1328         int slashEIndex = s.indexOf("\\E");
1329         if (slashEIndex == -1)
1330             return "\\Q" + s + "\\E";
1331 
1332         StringBuilder sb = new StringBuilder(s.length() * 2);
1333         sb.append("\\Q");
1334         slashEIndex = 0;
1335         int current = 0;
1336         while ((slashEIndex = s.indexOf("\\E", current)) != -1) {
1337             sb.append(s.substring(current, slashEIndex));
1338             current = slashEIndex + 2;
1339             sb.append("\\E\\\\E\\Q");
1340         }
1341         sb.append(s.substring(current, s.length()));
1342         sb.append("\\E");
1343         return sb.toString();
1344     }
1345 
1346     /**
1347      * Recompile the Pattern instance from a stream.  The original pattern
1348      * string is read in and the object tree is recompiled from it.
1349      */
readObject(java.io.ObjectInputStream s)1350     private void readObject(java.io.ObjectInputStream s)
1351         throws java.io.IOException, ClassNotFoundException {
1352 
1353         // Read in all fields
1354         s.defaultReadObject();
1355 
1356         // Android-removed: reimplement matching logic natively via ICU.
1357         // // Initialize counts
1358         // capturingGroupCount = 1;
1359         // localCount = 0;
1360 
1361         // Android-changed: Pattern is eagerly compiled() upon construction.
1362         /*
1363         // if length > 0, the Pattern is lazily compiled
1364         compiled = false;
1365         if (pattern.length() == 0) {
1366             root = new Start(lastAccept);
1367             matchRoot = lastAccept;
1368             compiled = true;
1369         }
1370         */
1371         compile();
1372     }
1373 
1374     // Android-changed: reimplement matching logic natively via ICU.
1375     // Dropped documentation reference to Start and LastNode implementation
1376     // details which do not apply on Android.
1377     /**
1378      * This private constructor is used to create all Patterns. The pattern
1379      * string and match flags are all that is needed to completely describe
1380      * a Pattern.
1381      */
Pattern(String p, int f)1382     private Pattern(String p, int f) {
1383         pattern = p;
1384         flags = f;
1385 
1386         // BEGIN Android-changed: Only specific flags are supported.
1387         /*
1388         // to use UNICODE_CASE if UNICODE_CHARACTER_CLASS present
1389         if ((flags & UNICODE_CHARACTER_CLASS) != 0)
1390             flags |= UNICODE_CASE;
1391 
1392         // Reset group index count
1393         capturingGroupCount = 1;
1394         localCount = 0;
1395         */
1396         if ((f & CANON_EQ) != 0) {
1397             throw new UnsupportedOperationException("CANON_EQ flag not supported");
1398         }
1399         int supportedFlags = CASE_INSENSITIVE | COMMENTS | DOTALL | LITERAL | MULTILINE | UNICODE_CASE | UNIX_LINES;
1400         if ((f & ~supportedFlags) != 0) {
1401             throw new IllegalArgumentException("Unsupported flags: " + (f & ~supportedFlags));
1402         }
1403         // END Android-changed: Only specific flags are supported.
1404 
1405         // BEGIN Android-removed: Pattern is eagerly compiled() upon construction.
1406         // if (pattern.length() > 0) {
1407         // END Android-removed: Pattern is eagerly compiled() upon construction.
1408             compile();
1409         // Android-removed: reimplement matching logic natively via ICU.
1410         /*
1411         } else {
1412             root = new Start(lastAccept);
1413             matchRoot = lastAccept;
1414         }
1415         */
1416     }
1417 
1418     // BEGIN Android-changed: reimplement matching logic natively via ICU.
1419     // Use native implementation instead of > 3000 lines of helper methods.
compile()1420     private void compile() throws PatternSyntaxException {
1421         if (pattern == null) {
1422             throw new NullPointerException("pattern == null");
1423         }
1424 
1425         String icuPattern = pattern;
1426         if ((flags & LITERAL) != 0) {
1427             icuPattern = quote(pattern);
1428         }
1429 
1430         // These are the flags natively supported by ICU.
1431         // They even have the same value in native code.
1432         int icuFlags = flags & (CASE_INSENSITIVE | COMMENTS | MULTILINE | DOTALL | UNIX_LINES);
1433         address = compileImpl(icuPattern, icuFlags);
1434         registry.registerNativeAllocation(this, address);
1435     }
1436 
compileImpl(String regex, int flags)1437     private static native long compileImpl(String regex, int flags);
getNativeFinalizer()1438     private static native long getNativeFinalizer();
1439     // END Android-changed: reimplement matching logic natively via ICU.
1440 
1441     /**
1442      * Creates a predicate which can be used to match a string.
1443      *
1444      * @return  The predicate which can be used for matching on a string
1445      * @since   1.8
1446      */
asPredicate()1447     public Predicate<String> asPredicate() {
1448         return s -> matcher(s).find();
1449     }
1450 
1451     /**
1452      * Creates a stream from the given input sequence around matches of this
1453      * pattern.
1454      *
1455      * <p> The stream returned by this method contains each substring of the
1456      * input sequence that is terminated by another subsequence that matches
1457      * this pattern or is terminated by the end of the input sequence.  The
1458      * substrings in the stream are in the order in which they occur in the
1459      * input. Trailing empty strings will be discarded and not encountered in
1460      * the stream.
1461      *
1462      * <p> If this pattern does not match any subsequence of the input then
1463      * the resulting stream has just one element, namely the input sequence in
1464      * string form.
1465      *
1466      * <p> When there is a positive-width match at the beginning of the input
1467      * sequence then an empty leading substring is included at the beginning
1468      * of the stream. A zero-width match at the beginning however never produces
1469      * such empty leading substring.
1470      *
1471      * <p> If the input sequence is mutable, it must remain constant during the
1472      * execution of the terminal stream operation.  Otherwise, the result of the
1473      * terminal stream operation is undefined.
1474      *
1475      * @param   input
1476      *          The character sequence to be split
1477      *
1478      * @return  The stream of strings computed by splitting the input
1479      *          around matches of this pattern
1480      * @see     #split(CharSequence)
1481      * @since   1.8
1482      */
splitAsStream(final CharSequence input)1483     public Stream<String> splitAsStream(final CharSequence input) {
1484         class MatcherIterator implements Iterator<String> {
1485             private final Matcher matcher;
1486             // The start position of the next sub-sequence of input
1487             // when current == input.length there are no more elements
1488             private int current;
1489             // null if the next element, if any, needs to obtained
1490             private String nextElement;
1491             // > 0 if there are N next empty elements
1492             private int emptyElementCount;
1493 
1494             MatcherIterator() {
1495                 this.matcher = matcher(input);
1496             }
1497 
1498             public String next() {
1499                 if (!hasNext())
1500                     throw new NoSuchElementException();
1501 
1502                 if (emptyElementCount == 0) {
1503                     String n = nextElement;
1504                     nextElement = null;
1505                     return n;
1506                 } else {
1507                     emptyElementCount--;
1508                     return "";
1509                 }
1510             }
1511 
1512             public boolean hasNext() {
1513                 if (nextElement != null || emptyElementCount > 0)
1514                     return true;
1515 
1516                 if (current == input.length())
1517                     return false;
1518 
1519                 // Consume the next matching element
1520                 // Count sequence of matching empty elements
1521                 while (matcher.find()) {
1522                     nextElement = input.subSequence(current, matcher.start()).toString();
1523                     current = matcher.end();
1524                     if (!nextElement.isEmpty()) {
1525                         return true;
1526                     } else if (current > 0) { // no empty leading substring for zero-width
1527                                               // match at the beginning of the input
1528                         emptyElementCount++;
1529                     }
1530                 }
1531 
1532                 // Consume last matching element
1533                 nextElement = input.subSequence(current, input.length()).toString();
1534                 current = input.length();
1535                 if (!nextElement.isEmpty()) {
1536                     return true;
1537                 } else {
1538                     // Ignore a terminal sequence of matching empty elements
1539                     emptyElementCount = 0;
1540                     nextElement = null;
1541                     return false;
1542                 }
1543             }
1544         }
1545         return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
1546                 new MatcherIterator(), Spliterator.ORDERED | Spliterator.NONNULL), false);
1547     }
1548 }
1549