• 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> Comparison to Perl 5 </h3>
679  *
680  * <p>The <code>Pattern</code> engine performs traditional NFA-based matching
681  * with ordered alternation as occurs in Perl 5.
682  *
683  * <p> Perl constructs not supported by this class: </p>
684  *
685  * <ul>
686  *    <li><p> Predefined character classes (Unicode character)
687  *    <p><tt>\X&nbsp;&nbsp;&nbsp;&nbsp;</tt>Match Unicode
688  *    <a href="http://www.unicode.org/reports/tr18/#Default_Grapheme_Clusters">
689  *    <i>extended grapheme cluster</i></a>
690  *    </p></li>
691  *
692  *    <li><p> The backreference constructs, <tt>\g{</tt><i>n</i><tt>}</tt> for
693  *    the <i>n</i><sup>th</sup><a href="#cg">capturing group</a> and
694  *    <tt>\g{</tt><i>name</i><tt>}</tt> for
695  *    <a href="#groupname">named-capturing group</a>.
696  *    </p></li>
697  *
698  *    <li><p> The named character construct, <tt>\N{</tt><i>name</i><tt>}</tt>
699  *    for a Unicode character by its name.
700  *    </p></li>
701  *
702  *    <li><p> The conditional constructs
703  *    <tt>(?(</tt><i>condition</i><tt>)</tt><i>X</i><tt>)</tt> and
704  *    <tt>(?(</tt><i>condition</i><tt>)</tt><i>X</i><tt>|</tt><i>Y</i><tt>)</tt>,
705  *    </p></li>
706  *
707  *    <li><p> The embedded code constructs <tt>(?{</tt><i>code</i><tt>})</tt>
708  *    and <tt>(??{</tt><i>code</i><tt>})</tt>,</p></li>
709  *
710  *    <li><p> The embedded comment syntax <tt>(?#comment)</tt>, and </p></li>
711  *
712  *    <li><p> The preprocessing operations <tt>\l</tt> <tt>&#92;u</tt>,
713  *    <tt>\L</tt>, and <tt>\U</tt>.  </p></li>
714  *
715  * </ul>
716  *
717  * <p> Constructs supported by this class but not by Perl: </p>
718  *
719  * <ul>
720  *
721  *    <li><p> Character-class union and intersection as described
722  *    <a href="#cc">above</a>.</p></li>
723  *
724  * </ul>
725  *
726  * <p> Notable differences from Perl: </p>
727  *
728  * <ul>
729  *
730  *    <li><p> In Perl, <tt>\1</tt> through <tt>\9</tt> are always interpreted
731  *    as back references; a backslash-escaped number greater than <tt>9</tt> is
732  *    treated as a back reference if at least that many subexpressions exist,
733  *    otherwise it is interpreted, if possible, as an octal escape.  In this
734  *    class octal escapes must always begin with a zero. In this class,
735  *    <tt>\1</tt> through <tt>\9</tt> are always interpreted as back
736  *    references, and a larger number is accepted as a back reference if at
737  *    least that many subexpressions exist at that point in the regular
738  *    expression, otherwise the parser will drop digits until the number is
739  *    smaller or equal to the existing number of groups or it is one digit.
740  *    </p></li>
741  *
742  *    <li><p> Perl uses the <tt>g</tt> flag to request a match that resumes
743  *    where the last match left off.  This functionality is provided implicitly
744  *    by the {@link Matcher} class: Repeated invocations of the {@link
745  *    Matcher#find find} method will resume where the last match left off,
746  *    unless the matcher is reset.  </p></li>
747  *
748  *    <li><p> In Perl, embedded flags at the top level of an expression affect
749  *    the whole expression.  In this class, embedded flags always take effect
750  *    at the point at which they appear, whether they are at the top level or
751  *    within a group; in the latter case, flags are restored at the end of the
752  *    group just as in Perl.  </p></li>
753  *
754  * </ul>
755  *
756  *
757  * <p> For a more precise description of the behavior of regular expression
758  * constructs, please see <a href="http://www.oreilly.com/catalog/regex3/">
759  * <i>Mastering Regular Expressions, 3nd Edition</i>, Jeffrey E. F. Friedl,
760  * O'Reilly and Associates, 2006.</a>
761  * </p>
762  *
763  * @see java.lang.String#split(String, int)
764  * @see java.lang.String#split(String)
765  *
766  * @author      Mike McCloskey
767  * @author      Mark Reinhold
768  * @author      JSR-51 Expert Group
769  * @since       1.4
770  * @spec        JSR-51
771  */
772 
773 public final class Pattern
774     implements java.io.Serializable
775 {
776 
777     /**
778      * Regular expression modifier values.  Instead of being passed as
779      * arguments, they can also be passed as inline modifiers.
780      * For example, the following statements have the same effect.
781      * <pre>
782      * RegExp r1 = RegExp.compile("abc", Pattern.I|Pattern.M);
783      * RegExp r2 = RegExp.compile("(?im)abc", 0);
784      * </pre>
785      *
786      * The flags are duplicated so that the familiar Perl match flag
787      * names are available.
788      */
789 
790     /**
791      * Enables Unix lines mode.
792      *
793      * <p> In this mode, only the <tt>'\n'</tt> line terminator is recognized
794      * in the behavior of <tt>.</tt>, <tt>^</tt>, and <tt>$</tt>.
795      *
796      * <p> Unix lines mode can also be enabled via the embedded flag
797      * expression&nbsp;<tt>(?d)</tt>.
798      */
799     public static final int UNIX_LINES = 0x01;
800 
801     /**
802      * Enables case-insensitive matching.
803      *
804      * <p> By default, case-insensitive matching assumes that only characters
805      * in the US-ASCII charset are being matched.  Unicode-aware
806      * case-insensitive matching can be enabled by specifying the {@link
807      * #UNICODE_CASE} flag in conjunction with this flag.
808      *
809      * <p> Case-insensitive matching can also be enabled via the embedded flag
810      * expression&nbsp;<tt>(?i)</tt>.
811      *
812      * <p> Specifying this flag may impose a slight performance penalty.  </p>
813      */
814     public static final int CASE_INSENSITIVE = 0x02;
815 
816     /**
817      * Permits whitespace and comments in pattern.
818      *
819      * <p> In this mode, whitespace is ignored, and embedded comments starting
820      * with <tt>#</tt> are ignored until the end of a line.
821      *
822      * <p> Comments mode can also be enabled via the embedded flag
823      * expression&nbsp;<tt>(?x)</tt>.
824      */
825     public static final int COMMENTS = 0x04;
826 
827     /**
828      * Enables multiline mode.
829      *
830      * <p> In multiline mode the expressions <tt>^</tt> and <tt>$</tt> match
831      * just after or just before, respectively, a line terminator or the end of
832      * the input sequence.  By default these expressions only match at the
833      * beginning and the end of the entire input sequence.
834      *
835      * <p> Multiline mode can also be enabled via the embedded flag
836      * expression&nbsp;<tt>(?m)</tt>.  </p>
837      */
838     public static final int MULTILINE = 0x08;
839 
840     /**
841      * Enables literal parsing of the pattern.
842      *
843      * <p> When this flag is specified then the input string that specifies
844      * the pattern is treated as a sequence of literal characters.
845      * Metacharacters or escape sequences in the input sequence will be
846      * given no special meaning.
847      *
848      * <p>The flags CASE_INSENSITIVE and UNICODE_CASE retain their impact on
849      * matching when used in conjunction with this flag. The other flags
850      * become superfluous.
851      *
852      * <p> There is no embedded flag character for enabling literal parsing.
853      * @since 1.5
854      */
855     public static final int LITERAL = 0x10;
856 
857     /**
858      * Enables dotall mode.
859      *
860      * <p> In dotall mode, the expression <tt>.</tt> matches any character,
861      * including a line terminator.  By default this expression does not match
862      * line terminators.
863      *
864      * <p> Dotall mode can also be enabled via the embedded flag
865      * expression&nbsp;<tt>(?s)</tt>.  (The <tt>s</tt> is a mnemonic for
866      * "single-line" mode, which is what this is called in Perl.)  </p>
867      */
868     public static final int DOTALL = 0x20;
869 
870     /**
871      * Enables Unicode-aware case folding.
872      *
873      * <p> When this flag is specified then case-insensitive matching, when
874      * enabled by the {@link #CASE_INSENSITIVE} flag, is done in a manner
875      * consistent with the Unicode Standard.  By default, case-insensitive
876      * matching assumes that only characters in the US-ASCII charset are being
877      * matched.
878      *
879      * <p> Unicode-aware case folding can also be enabled via the embedded flag
880      * expression&nbsp;<tt>(?u)</tt>.
881      *
882      * <p> Specifying this flag may impose a performance penalty.  </p>
883      */
884     public static final int UNICODE_CASE = 0x40;
885 
886     // Android-changed: Android does not support CANON_EQ flag.
887     /**
888      * This flag is not supported on Android.
889      *
890      * Enables canonical equivalence.
891      *
892      * <p> When this flag is specified then two characters will be considered
893      * to match if, and only if, their full canonical decompositions match.
894      * The expression <tt>"a&#92;u030A"</tt>, for example, will match the
895      * string <tt>"&#92;u00E5"</tt> when this flag is specified.  By default,
896      * matching does not take canonical equivalence into account.
897      *
898      * <p> There is no embedded flag character for enabling canonical
899      * equivalence.
900      *
901      * <p> Specifying this flag may impose a performance penalty.  </p>
902      */
903     public static final int CANON_EQ = 0x80;
904 
905     // Android-changed: Android always uses unicode character classes.
906     /**
907      * This flag is not supported on Android, and Unicode character classes are always
908      * used.
909      *
910      * Enables the Unicode version of <i>Predefined character classes</i> and
911      * <i>POSIX character classes</i> as defined by <a href="http://www.unicode.org/reports/tr18/"><i>Unicode Technical
912      * Standard #18: Unicode Regular Expression</i></a>
913      * <i>Annex C: Compatibility Properties</i>.
914      * <p>
915      *
916      * @since 1.7
917      */
918     public static final int UNICODE_CHARACTER_CLASS = 0x100;
919 
920     /* Pattern has only two serialized components: The pattern string
921      * and the flags, which are all that is needed to recompile the pattern
922      * when it is deserialized.
923      */
924 
925     /** use serialVersionUID from Merlin b59 for interoperability */
926     private static final long serialVersionUID = 5073258162644648461L;
927 
928     /**
929      * The original regular-expression pattern string.
930      *
931      * @serial
932      */
933     // Android-changed: reimplement matching logic natively via ICU.
934     // private String pattern;
935     private final String pattern;
936 
937     /**
938      * The original pattern flags.
939      *
940      * @serial
941      */
942     // Android-changed: reimplement matching logic natively via ICU.
943     // private int flags;
944     private final int flags;
945 
946     // BEGIN Android-changed: reimplement matching logic natively via ICU.
947     // We only need some tie-ins to native memory, instead of a large number
948     // of fields on the .java side.
949     /* package */ transient PatternNative nativePattern;
950     // END Android-changed: reimplement matching logic natively via ICU.
951 
952     /**
953      * Compiles the given regular expression into a pattern.
954      *
955      * @param  regex
956      *         The expression to be compiled
957      * @return the given regular expression compiled into a pattern
958      * @throws  PatternSyntaxException
959      *          If the expression's syntax is invalid
960      */
compile(String regex)961     public static Pattern compile(String regex) {
962         return new Pattern(regex, 0);
963     }
964 
965     // Android-changed: Android doesn't support CANON_EQ and UNICODE_CHARACTER_CLASS flags.
966     /**
967      * Compiles the given regular expression into a pattern with the given
968      * flags.
969      *
970      * @param  regex
971      *         The expression to be compiled
972      *
973      * @param  flags
974      *         Match flags, a bit mask that may include
975      *         {@link #CASE_INSENSITIVE}, {@link #MULTILINE}, {@link #DOTALL},
976      *         {@link #UNICODE_CASE}, {@link #UNIX_LINES}, {@link #LITERAL},
977      *         and {@link #COMMENTS}
978      *
979      * @return the given regular expression compiled into a pattern with the given flags
980      * @throws  IllegalArgumentException
981      *          If bit values other than those corresponding to the defined
982      *          match flags are set in <tt>flags</tt>
983      *
984      * @throws  PatternSyntaxException
985      *          If the expression's syntax is invalid
986      */
compile(String regex, int flags)987     public static Pattern compile(String regex, int flags) {
988         return new Pattern(regex, flags);
989     }
990 
991     /**
992      * Returns the regular expression from which this pattern was compiled.
993      *
994      * @return  The source of this pattern
995      */
pattern()996     public String pattern() {
997         return pattern;
998     }
999 
1000     /**
1001      * <p>Returns the string representation of this pattern. This
1002      * is the regular expression from which this pattern was
1003      * compiled.</p>
1004      *
1005      * @return  The string representation of this pattern
1006      * @since 1.5
1007      */
toString()1008     public String toString() {
1009         return pattern;
1010     }
1011 
1012     /**
1013      * Creates a matcher that will match the given input against this pattern.
1014      *
1015      * @param  input
1016      *         The character sequence to be matched
1017      *
1018      * @return  A new matcher for this pattern
1019      */
matcher(CharSequence input)1020     public Matcher matcher(CharSequence input) {
1021         // Android-removed: Pattern is eagerly compiled() upon construction.
1022         /*
1023         if (!compiled) {
1024             synchronized(this) {
1025                 if (!compiled)
1026                     compile();
1027             }
1028         }
1029         */
1030         Matcher m = new Matcher(this, input);
1031         return m;
1032     }
1033 
1034     /**
1035      * Returns this pattern's match flags.
1036      *
1037      * @return  The match flags specified when this pattern was compiled
1038      */
flags()1039     public int flags() {
1040         return flags;
1041     }
1042 
1043     /**
1044      * Compiles the given regular expression and attempts to match the given
1045      * input against it.
1046      *
1047      * <p> An invocation of this convenience method of the form
1048      *
1049      * <blockquote><pre>
1050      * Pattern.matches(regex, input);</pre></blockquote>
1051      *
1052      * behaves in exactly the same way as the expression
1053      *
1054      * <blockquote><pre>
1055      * Pattern.compile(regex).matcher(input).matches()</pre></blockquote>
1056      *
1057      * <p> If a pattern is to be used multiple times, compiling it once and reusing
1058      * it will be more efficient than invoking this method each time.  </p>
1059      *
1060      * @param  regex
1061      *         The expression to be compiled
1062      *
1063      * @param  input
1064      *         The character sequence to be matched
1065      * @return whether or not the regular expression matches on the input
1066      * @throws  PatternSyntaxException
1067      *          If the expression's syntax is invalid
1068      */
matches(String regex, CharSequence input)1069     public static boolean matches(String regex, CharSequence input) {
1070         Pattern p = Pattern.compile(regex);
1071         Matcher m = p.matcher(input);
1072         return m.matches();
1073     }
1074 
1075     // Android-changed: Adopt split() behavior change only for apps targeting API > 28.
1076     // http://b/109659282#comment7
1077     /**
1078      * Splits the given input sequence around matches of this pattern.
1079      *
1080      * <p> The array returned by this method contains each substring of the
1081      * input sequence that is terminated by another subsequence that matches
1082      * this pattern or is terminated by the end of the input sequence.  The
1083      * substrings in the array are in the order in which they occur in the
1084      * input. If this pattern does not match any subsequence of the input then
1085      * the resulting array has just one element, namely the input sequence in
1086      * string form.
1087      *
1088      * <p> When there is a positive-width match at the beginning of the input
1089      * sequence then an empty leading substring is included at the beginning
1090      * of the resulting array. A zero-width match at the beginning however
1091      * can only produce such an empty leading substring for apps running on or
1092      * targeting API versions <= 28.
1093      *
1094      * <p> The <tt>limit</tt> parameter controls the number of times the
1095      * pattern is applied and therefore affects the length of the resulting
1096      * array.  If the limit <i>n</i> is greater than zero then the pattern
1097      * will be applied at most <i>n</i>&nbsp;-&nbsp;1 times, the array's
1098      * length will be no greater than <i>n</i>, and the array's last entry
1099      * will contain all input beyond the last matched delimiter.  If <i>n</i>
1100      * is non-positive then the pattern will be applied as many times as
1101      * possible and the array can have any length.  If <i>n</i> is zero then
1102      * the pattern will be applied as many times as possible, the array can
1103      * have any length, and trailing empty strings will be discarded.
1104      *
1105      * <p> The input <tt>"boo:and:foo"</tt>, for example, yields the following
1106      * results with these parameters:
1107      *
1108      * <blockquote><table cellpadding=1 cellspacing=0
1109      *              summary="Split examples showing regex, limit, and result">
1110      * <tr><th align="left"><i>Regex&nbsp;&nbsp;&nbsp;&nbsp;</i></th>
1111      *     <th align="left"><i>Limit&nbsp;&nbsp;&nbsp;&nbsp;</i></th>
1112      *     <th align="left"><i>Result&nbsp;&nbsp;&nbsp;&nbsp;</i></th></tr>
1113      * <tr><td align=center>:</td>
1114      *     <td align=center>2</td>
1115      *     <td><tt>{ "boo", "and:foo" }</tt></td></tr>
1116      * <tr><td align=center>:</td>
1117      *     <td align=center>5</td>
1118      *     <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
1119      * <tr><td align=center>:</td>
1120      *     <td align=center>-2</td>
1121      *     <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
1122      * <tr><td align=center>o</td>
1123      *     <td align=center>5</td>
1124      *     <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
1125      * <tr><td align=center>o</td>
1126      *     <td align=center>-2</td>
1127      *     <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
1128      * <tr><td align=center>o</td>
1129      *     <td align=center>0</td>
1130      *     <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
1131      * </table></blockquote>
1132      *
1133      * @param  input
1134      *         The character sequence to be split
1135      *
1136      * @param  limit
1137      *         The result threshold, as described above
1138      *
1139      * @return  The array of strings computed by splitting the input
1140      *          around matches of this pattern
1141      */
split(CharSequence input, int limit)1142     public String[] split(CharSequence input, int limit) {
1143         // BEGIN Android-added: fastSplit() to speed up simple cases.
1144         String[] fast = fastSplit(pattern, input.toString(), limit);
1145         if (fast != null) {
1146             return fast;
1147         }
1148         // END Android-added: fastSplit() to speed up simple cases.
1149         int index = 0;
1150         boolean matchLimited = limit > 0;
1151         ArrayList<String> matchList = new ArrayList<>();
1152         Matcher m = matcher(input);
1153 
1154         // Add segments before each match found
1155         while(m.find()) {
1156             if (!matchLimited || matchList.size() < limit - 1) {
1157                 if (index == 0 && index == m.start() && m.start() == m.end()) {
1158                     // no empty leading substring included for zero-width match
1159                     // at the beginning of the input char sequence.
1160                     // BEGIN Android-changed: split() compat behavior for apps targeting <= 28.
1161                     // continue;
1162                     int targetSdkVersion = VMRuntime.getRuntime().getTargetSdkVersion();
1163                     if (targetSdkVersion > 28) {
1164                         continue;
1165                     }
1166                     // END Android-changed: split() compat behavior for apps targeting <= 28.
1167                 }
1168                 String match = input.subSequence(index, m.start()).toString();
1169                 matchList.add(match);
1170                 index = m.end();
1171             } else if (matchList.size() == limit - 1) { // last one
1172                 String match = input.subSequence(index,
1173                                                  input.length()).toString();
1174                 matchList.add(match);
1175                 index = m.end();
1176             }
1177         }
1178 
1179         // If no match was found, return this
1180         if (index == 0)
1181             return new String[] {input.toString()};
1182 
1183         // Add remaining segment
1184         if (!matchLimited || matchList.size() < limit)
1185             matchList.add(input.subSequence(index, input.length()).toString());
1186 
1187         // Construct result
1188         int resultSize = matchList.size();
1189         if (limit == 0)
1190             while (resultSize > 0 && matchList.get(resultSize-1).equals(""))
1191                 resultSize--;
1192         String[] result = new String[resultSize];
1193         return matchList.subList(0, resultSize).toArray(result);
1194     }
1195 
1196     // BEGIN Android-added: fastSplit() to speed up simple cases.
1197     private static final String FASTSPLIT_METACHARACTERS = "\\?*+[](){}^$.|";
1198 
1199     /**
1200      * Returns a result equivalent to {@code s.split(separator, limit)} if it's able
1201      * to compute it more cheaply than native impl, or null if the caller should fall back to
1202      * using native impl.
1203      *
1204      *  fastpath will work  if the regex is a
1205      *   (1)one-char String and this character is not one of the
1206      *      RegEx's meta characters ".$|()[{^?*+\\", or
1207      *   (2)two-char String and the first char is the backslash and
1208      *      the second is one of regEx's meta characters ".$|()[{^?*+\\".
1209      * @hide
1210      */
fastSplit(String re, String input, int limit)1211     public static String[] fastSplit(String re, String input, int limit) {
1212         // Can we do it cheaply?
1213         int len = re.length();
1214         if (len == 0) {
1215             return null;
1216         }
1217         char ch = re.charAt(0);
1218         if (len == 1 && FASTSPLIT_METACHARACTERS.indexOf(ch) == -1) {
1219             // We're looking for a single non-metacharacter. Easy.
1220         } else if (len == 2 && ch == '\\') {
1221             // We're looking for a quoted character.
1222             // Quoted metacharacters are effectively single non-metacharacters.
1223             ch = re.charAt(1);
1224             if (FASTSPLIT_METACHARACTERS.indexOf(ch) == -1) {
1225                 return null;
1226             }
1227         } else {
1228             return null;
1229         }
1230 
1231         // We can do this cheaply...
1232 
1233         // Unlike Perl, which considers the result of splitting the empty string to be the empty
1234         // array, Java returns an array containing the empty string.
1235         if (input.isEmpty()) {
1236             return new String[] { "" };
1237         }
1238 
1239         // Count separators
1240         int separatorCount = 0;
1241         int begin = 0;
1242         int end;
1243         while (separatorCount + 1 != limit && (end = input.indexOf(ch, begin)) != -1) {
1244             ++separatorCount;
1245             begin = end + 1;
1246         }
1247         int lastPartEnd = input.length();
1248         if (limit == 0 && begin == lastPartEnd) {
1249             // Last part is empty for limit == 0, remove all trailing empty matches.
1250             if (separatorCount == lastPartEnd) {
1251                 // Input contains only separators.
1252                 return EmptyArray.STRING;
1253             }
1254             // Find the beginning of trailing separators.
1255             do {
1256                 --begin;
1257             } while (input.charAt(begin - 1) == ch);
1258             // Reduce separatorCount and fix lastPartEnd.
1259             separatorCount -= input.length() - begin;
1260             lastPartEnd = begin;
1261         }
1262 
1263         // Collect the result parts.
1264         String[] result = new String[separatorCount + 1];
1265         begin = 0;
1266         for (int i = 0; i != separatorCount; ++i) {
1267             end = input.indexOf(ch, begin);
1268             result[i] = input.substring(begin, end);
1269             begin = end + 1;
1270         }
1271         // Add last part.
1272         result[separatorCount] = input.substring(begin, lastPartEnd);
1273         return result;
1274     }
1275     // END Android-added: fastSplit() to speed up simple cases.
1276 
1277     /**
1278      * Splits the given input sequence around matches of this pattern.
1279      *
1280      * <p> This method works as if by invoking the two-argument {@link
1281      * #split(java.lang.CharSequence, int) split} method with the given input
1282      * sequence and a limit argument of zero.  Trailing empty strings are
1283      * therefore not included in the resulting array. </p>
1284      *
1285      * <p> The input <tt>"boo:and:foo"</tt>, for example, yields the following
1286      * results with these expressions:
1287      *
1288      * <blockquote><table cellpadding=1 cellspacing=0
1289      *              summary="Split examples showing regex and result">
1290      * <tr><th align="left"><i>Regex&nbsp;&nbsp;&nbsp;&nbsp;</i></th>
1291      *     <th align="left"><i>Result</i></th></tr>
1292      * <tr><td align=center>:</td>
1293      *     <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
1294      * <tr><td align=center>o</td>
1295      *     <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
1296      * </table></blockquote>
1297      *
1298      *
1299      * @param  input
1300      *         The character sequence to be split
1301      *
1302      * @return  The array of strings computed by splitting the input
1303      *          around matches of this pattern
1304      */
split(CharSequence input)1305     public String[] split(CharSequence input) {
1306         return split(input, 0);
1307     }
1308 
1309     /**
1310      * Returns a literal pattern <code>String</code> for the specified
1311      * <code>String</code>.
1312      *
1313      * <p>This method produces a <code>String</code> that can be used to
1314      * create a <code>Pattern</code> that would match the string
1315      * <code>s</code> as if it were a literal pattern.</p> Metacharacters
1316      * or escape sequences in the input sequence will be given no special
1317      * meaning.
1318      *
1319      * @param  s The string to be literalized
1320      * @return  A literal string replacement
1321      * @since 1.5
1322      */
quote(String s)1323     public static String quote(String s) {
1324         int slashEIndex = s.indexOf("\\E");
1325         if (slashEIndex == -1)
1326             return "\\Q" + s + "\\E";
1327 
1328         StringBuilder sb = new StringBuilder(s.length() * 2);
1329         sb.append("\\Q");
1330         slashEIndex = 0;
1331         int current = 0;
1332         while ((slashEIndex = s.indexOf("\\E", current)) != -1) {
1333             sb.append(s.substring(current, slashEIndex));
1334             current = slashEIndex + 2;
1335             sb.append("\\E\\\\E\\Q");
1336         }
1337         sb.append(s.substring(current, s.length()));
1338         sb.append("\\E");
1339         return sb.toString();
1340     }
1341 
1342     /**
1343      * Recompile the Pattern instance from a stream.  The original pattern
1344      * string is read in and the object tree is recompiled from it.
1345      */
readObject(java.io.ObjectInputStream s)1346     private void readObject(java.io.ObjectInputStream s)
1347         throws java.io.IOException, ClassNotFoundException {
1348 
1349         // Read in all fields
1350         s.defaultReadObject();
1351 
1352         // Android-removed: reimplement matching logic natively via ICU.
1353         // // Initialize counts
1354         // capturingGroupCount = 1;
1355         // localCount = 0;
1356 
1357         // Android-changed: Pattern is eagerly compiled() upon construction.
1358         /*
1359         // if length > 0, the Pattern is lazily compiled
1360         compiled = false;
1361         if (pattern.length() == 0) {
1362             root = new Start(lastAccept);
1363             matchRoot = lastAccept;
1364             compiled = true;
1365         }
1366         */
1367         compile();
1368     }
1369 
1370     // Android-changed: reimplement matching logic natively via ICU.
1371     // Dropped documentation reference to Start and LastNode implementation
1372     // details which do not apply on Android.
1373     /**
1374      * This private constructor is used to create all Patterns. The pattern
1375      * string and match flags are all that is needed to completely describe
1376      * a Pattern.
1377      */
Pattern(String p, int f)1378     private Pattern(String p, int f) {
1379         pattern = p;
1380         flags = f;
1381 
1382         // BEGIN Android-changed: Only specific flags are supported.
1383         /*
1384         // to use UNICODE_CASE if UNICODE_CHARACTER_CLASS present
1385         if ((flags & UNICODE_CHARACTER_CLASS) != 0)
1386             flags |= UNICODE_CASE;
1387 
1388         // Reset group index count
1389         capturingGroupCount = 1;
1390         localCount = 0;
1391         */
1392         if ((f & CANON_EQ) != 0) {
1393             throw new UnsupportedOperationException("CANON_EQ flag not supported");
1394         }
1395         int supportedFlags = CASE_INSENSITIVE | COMMENTS | DOTALL | LITERAL | MULTILINE | UNICODE_CASE | UNIX_LINES;
1396         if ((f & ~supportedFlags) != 0) {
1397             throw new IllegalArgumentException("Unsupported flags: " + (f & ~supportedFlags));
1398         }
1399         // END Android-changed: Only specific flags are supported.
1400 
1401         // BEGIN Android-removed: Pattern is eagerly compiled() upon construction.
1402         // if (pattern.length() > 0) {
1403         // END Android-removed: Pattern is eagerly compiled() upon construction.
1404             compile();
1405         // Android-removed: reimplement matching logic natively via ICU.
1406         /*
1407         } else {
1408             root = new Start(lastAccept);
1409             matchRoot = lastAccept;
1410         }
1411         */
1412     }
1413 
1414     // BEGIN Android-changed: reimplement matching logic natively via ICU.
1415     // Use native implementation instead of > 3000 lines of helper methods.
compile()1416     private void compile() throws PatternSyntaxException {
1417         if (pattern == null) {
1418             throw new NullPointerException("pattern == null");
1419         }
1420 
1421         String icuPattern = pattern;
1422         if ((flags & LITERAL) != 0) {
1423             icuPattern = quote(pattern);
1424         }
1425 
1426         // These are the flags natively supported by ICU.
1427         // They even have the same value in native code.
1428         int icuFlags = flags & (CASE_INSENSITIVE | COMMENTS | MULTILINE | DOTALL | UNIX_LINES);
1429         nativePattern = PatternNative.create(icuPattern, icuFlags);
1430     }
1431     // END Android-changed: reimplement matching logic natively via ICU.
1432 
1433     /**
1434      * Creates a predicate which can be used to match a string.
1435      *
1436      * @return  The predicate which can be used for matching on a string
1437      * @since   1.8
1438      */
asPredicate()1439     public Predicate<String> asPredicate() {
1440         return s -> matcher(s).find();
1441     }
1442 
1443     /**
1444      * Creates a stream from the given input sequence around matches of this
1445      * pattern.
1446      *
1447      * <p> The stream returned by this method contains each substring of the
1448      * input sequence that is terminated by another subsequence that matches
1449      * this pattern or is terminated by the end of the input sequence.  The
1450      * substrings in the stream are in the order in which they occur in the
1451      * input. Trailing empty strings will be discarded and not encountered in
1452      * the stream.
1453      *
1454      * <p> If this pattern does not match any subsequence of the input then
1455      * the resulting stream has just one element, namely the input sequence in
1456      * string form.
1457      *
1458      * <p> When there is a positive-width match at the beginning of the input
1459      * sequence then an empty leading substring is included at the beginning
1460      * of the stream. A zero-width match at the beginning however never produces
1461      * such empty leading substring.
1462      *
1463      * <p> If the input sequence is mutable, it must remain constant during the
1464      * execution of the terminal stream operation.  Otherwise, the result of the
1465      * terminal stream operation is undefined.
1466      *
1467      * @param   input
1468      *          The character sequence to be split
1469      *
1470      * @return  The stream of strings computed by splitting the input
1471      *          around matches of this pattern
1472      * @see     #split(CharSequence)
1473      * @since   1.8
1474      */
splitAsStream(final CharSequence input)1475     public Stream<String> splitAsStream(final CharSequence input) {
1476         class MatcherIterator implements Iterator<String> {
1477             private final Matcher matcher;
1478             // The start position of the next sub-sequence of input
1479             // when current == input.length there are no more elements
1480             private int current;
1481             // null if the next element, if any, needs to obtained
1482             private String nextElement;
1483             // > 0 if there are N next empty elements
1484             private int emptyElementCount;
1485 
1486             MatcherIterator() {
1487                 this.matcher = matcher(input);
1488             }
1489 
1490             public String next() {
1491                 if (!hasNext())
1492                     throw new NoSuchElementException();
1493 
1494                 if (emptyElementCount == 0) {
1495                     String n = nextElement;
1496                     nextElement = null;
1497                     return n;
1498                 } else {
1499                     emptyElementCount--;
1500                     return "";
1501                 }
1502             }
1503 
1504             public boolean hasNext() {
1505                 if (nextElement != null || emptyElementCount > 0)
1506                     return true;
1507 
1508                 if (current == input.length())
1509                     return false;
1510 
1511                 // Consume the next matching element
1512                 // Count sequence of matching empty elements
1513                 while (matcher.find()) {
1514                     nextElement = input.subSequence(current, matcher.start()).toString();
1515                     current = matcher.end();
1516                     if (!nextElement.isEmpty()) {
1517                         return true;
1518                     } else if (current > 0) { // no empty leading substring for zero-width
1519                                               // match at the beginning of the input
1520                         emptyElementCount++;
1521                     }
1522                 }
1523 
1524                 // Consume last matching element
1525                 nextElement = input.subSequence(current, input.length()).toString();
1526                 current = input.length();
1527                 if (!nextElement.isEmpty()) {
1528                     return true;
1529                 } else {
1530                     // Ignore a terminal sequence of matching empty elements
1531                     emptyElementCount = 0;
1532                     nextElement = null;
1533                     return false;
1534                 }
1535             }
1536         }
1537         return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
1538                 new MatcherIterator(), Spliterator.ORDERED | Spliterator.NONNULL), false);
1539     }
1540 }
1541