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