1 /*
2 * Copyright 1999-2007 Sun Microsystems, Inc. All Rights Reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Sun designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Sun in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
22 * CA 95054 USA or visit www.sun.com if you need additional information or
23 * have any questions.
24 */
25
26 package java.util.regex;
27
28 import java.security.AccessController;
29 import java.security.PrivilegedAction;
30 import java.text.CharacterIterator;
31 import java.text.Normalizer;
32 import java.util.ArrayList;
33 import java.util.HashMap;
34 import java.util.Arrays;
35
36
37 /**
38 * A compiled representation of a regular expression.
39 *
40 * <p> A regular expression, specified as a string, must first be compiled into
41 * an instance of this class. The resulting pattern can then be used to create
42 * a {@link Matcher} object that can match arbitrary {@link
43 * java.lang.CharSequence </code>character sequences<code>} against the regular
44 * expression. All of the state involved in performing a match resides in the
45 * matcher, so many matchers can share the same pattern.
46 *
47 * <p> A typical invocation sequence is thus
48 *
49 * <blockquote><pre>
50 * Pattern p = Pattern.{@link #compile compile}("a*b");
51 * Matcher m = p.{@link #matcher matcher}("aaaaab");
52 * boolean b = m.{@link Matcher#matches matches}();</pre></blockquote>
53 *
54 * <p> A {@link #matches matches} method is defined by this class as a
55 * convenience for when a regular expression is used just once. This method
56 * compiles an expression and matches an input sequence against it in a single
57 * invocation. The statement
58 *
59 * <blockquote><pre>
60 * boolean b = Pattern.matches("a*b", "aaaaab");</pre></blockquote>
61 *
62 * is equivalent to the three statements above, though for repeated matches it
63 * is less efficient since it does not allow the compiled pattern to be reused.
64 *
65 * <p> Instances of this class are immutable and are safe for use by multiple
66 * concurrent threads. Instances of the {@link Matcher} class are not safe for
67 * such use.
68 *
69 *
70 * <a name="sum">
71 * <h4> Summary of regular-expression constructs </h4>
72 *
73 * <table border="0" cellpadding="1" cellspacing="0"
74 * summary="Regular expression constructs, and what they match">
75 *
76 * <tr align="left">
77 * <th bgcolor="#CCCCFF" align="left" id="construct">Construct</th>
78 * <th bgcolor="#CCCCFF" align="left" id="matches">Matches</th>
79 * </tr>
80 *
81 * <tr><th> </th></tr>
82 * <tr align="left"><th colspan="2" id="characters">Characters</th></tr>
83 *
84 * <tr><td valign="top" headers="construct characters"><i>x</i></td>
85 * <td headers="matches">The character <i>x</i></td></tr>
86 * <tr><td valign="top" headers="construct characters"><tt>\\</tt></td>
87 * <td headers="matches">The backslash character</td></tr>
88 * <tr><td valign="top" headers="construct characters"><tt>\0</tt><i>n</i></td>
89 * <td headers="matches">The character with octal value <tt>0</tt><i>n</i>
90 * (0 <tt><=</tt> <i>n</i> <tt><=</tt> 7)</td></tr>
91 * <tr><td valign="top" headers="construct characters"><tt>\0</tt><i>nn</i></td>
92 * <td headers="matches">The character with octal value <tt>0</tt><i>nn</i>
93 * (0 <tt><=</tt> <i>n</i> <tt><=</tt> 7)</td></tr>
94 * <tr><td valign="top" headers="construct characters"><tt>\0</tt><i>mnn</i></td>
95 * <td headers="matches">The character with octal value <tt>0</tt><i>mnn</i>
96 * (0 <tt><=</tt> <i>m</i> <tt><=</tt> 3,
97 * 0 <tt><=</tt> <i>n</i> <tt><=</tt> 7)</td></tr>
98 * <tr><td valign="top" headers="construct characters"><tt>\x</tt><i>hh</i></td>
99 * <td headers="matches">The character with hexadecimal value <tt>0x</tt><i>hh</i></td></tr>
100 * <tr><td valign="top" headers="construct characters"><tt>\u</tt><i>hhhh</i></td>
101 * <td headers="matches">The character with hexadecimal value <tt>0x</tt><i>hhhh</i></td></tr>
102 * <tr><td valign="top" headers="matches"><tt>\t</tt></td>
103 * <td headers="matches">The tab character (<tt>'\u0009'</tt>)</td></tr>
104 * <tr><td valign="top" headers="construct characters"><tt>\n</tt></td>
105 * <td headers="matches">The newline (line feed) character (<tt>'\u000A'</tt>)</td></tr>
106 * <tr><td valign="top" headers="construct characters"><tt>\r</tt></td>
107 * <td headers="matches">The carriage-return character (<tt>'\u000D'</tt>)</td></tr>
108 * <tr><td valign="top" headers="construct characters"><tt>\f</tt></td>
109 * <td headers="matches">The form-feed character (<tt>'\u000C'</tt>)</td></tr>
110 * <tr><td valign="top" headers="construct characters"><tt>\a</tt></td>
111 * <td headers="matches">The alert (bell) character (<tt>'\u0007'</tt>)</td></tr>
112 * <tr><td valign="top" headers="construct characters"><tt>\e</tt></td>
113 * <td headers="matches">The escape character (<tt>'\u001B'</tt>)</td></tr>
114 * <tr><td valign="top" headers="construct characters"><tt>\c</tt><i>x</i></td>
115 * <td headers="matches">The control character corresponding to <i>x</i></td></tr>
116 *
117 * <tr><th> </th></tr>
118 * <tr align="left"><th colspan="2" id="classes">Character classes</th></tr>
119 *
120 * <tr><td valign="top" headers="construct classes"><tt>[abc]</tt></td>
121 * <td headers="matches"><tt>a</tt>, <tt>b</tt>, or <tt>c</tt> (simple class)</td></tr>
122 * <tr><td valign="top" headers="construct classes"><tt>[^abc]</tt></td>
123 * <td headers="matches">Any character except <tt>a</tt>, <tt>b</tt>, or <tt>c</tt> (negation)</td></tr>
124 * <tr><td valign="top" headers="construct classes"><tt>[a-zA-Z]</tt></td>
125 * <td headers="matches"><tt>a</tt> through <tt>z</tt>
126 * or <tt>A</tt> through <tt>Z</tt>, inclusive (range)</td></tr>
127 * <tr><td valign="top" headers="construct classes"><tt>[a-d[m-p]]</tt></td>
128 * <td headers="matches"><tt>a</tt> through <tt>d</tt>,
129 * or <tt>m</tt> through <tt>p</tt>: <tt>[a-dm-p]</tt> (union)</td></tr>
130 * <tr><td valign="top" headers="construct classes"><tt>[a-z&&[def]]</tt></td>
131 * <td headers="matches"><tt>d</tt>, <tt>e</tt>, or <tt>f</tt> (intersection)</tr>
132 * <tr><td valign="top" headers="construct classes"><tt>[a-z&&[^bc]]</tt></td>
133 * <td headers="matches"><tt>a</tt> through <tt>z</tt>,
134 * except for <tt>b</tt> and <tt>c</tt>: <tt>[ad-z]</tt> (subtraction)</td></tr>
135 * <tr><td valign="top" headers="construct classes"><tt>[a-z&&[^m-p]]</tt></td>
136 * <td headers="matches"><tt>a</tt> through <tt>z</tt>,
137 * and not <tt>m</tt> through <tt>p</tt>: <tt>[a-lq-z]</tt>(subtraction)</td></tr>
138 * <tr><th> </th></tr>
139 *
140 * <tr align="left"><th colspan="2" id="predef">Predefined character classes</th></tr>
141 *
142 * <tr><td valign="top" headers="construct predef"><tt>.</tt></td>
143 * <td headers="matches">Any character (may or may not match <a href="#lt">line terminators</a>)</td></tr>
144 * <tr><td valign="top" headers="construct predef"><tt>\d</tt></td>
145 * <td headers="matches">A digit: <tt>[0-9]</tt></td></tr>
146 * <tr><td valign="top" headers="construct predef"><tt>\D</tt></td>
147 * <td headers="matches">A non-digit: <tt>[^0-9]</tt></td></tr>
148 * <tr><td valign="top" headers="construct predef"><tt>\s</tt></td>
149 * <td headers="matches">A whitespace character: <tt>[ \t\n\x0B\f\r]</tt></td></tr>
150 * <tr><td valign="top" headers="construct predef"><tt>\S</tt></td>
151 * <td headers="matches">A non-whitespace character: <tt>[^\s]</tt></td></tr>
152 * <tr><td valign="top" headers="construct predef"><tt>\w</tt></td>
153 * <td headers="matches">A word character: <tt>[a-zA-Z_0-9]</tt></td></tr>
154 * <tr><td valign="top" headers="construct predef"><tt>\W</tt></td>
155 * <td headers="matches">A non-word character: <tt>[^\w]</tt></td></tr>
156 *
157 * <tr><th> </th></tr>
158 * <tr align="left"><th colspan="2" id="posix">POSIX character classes</b> (US-ASCII only)<b></th></tr>
159 *
160 * <tr><td valign="top" headers="construct posix"><tt>\p{Lower}</tt></td>
161 * <td headers="matches">A lower-case alphabetic character: <tt>[a-z]</tt></td></tr>
162 * <tr><td valign="top" headers="construct posix"><tt>\p{Upper}</tt></td>
163 * <td headers="matches">An upper-case alphabetic character:<tt>[A-Z]</tt></td></tr>
164 * <tr><td valign="top" headers="construct posix"><tt>\p{ASCII}</tt></td>
165 * <td headers="matches">All ASCII:<tt>[\x00-\x7F]</tt></td></tr>
166 * <tr><td valign="top" headers="construct posix"><tt>\p{Alpha}</tt></td>
167 * <td headers="matches">An alphabetic character:<tt>[\p{Lower}\p{Upper}]</tt></td></tr>
168 * <tr><td valign="top" headers="construct posix"><tt>\p{Digit}</tt></td>
169 * <td headers="matches">A decimal digit: <tt>[0-9]</tt></td></tr>
170 * <tr><td valign="top" headers="construct posix"><tt>\p{Alnum}</tt></td>
171 * <td headers="matches">An alphanumeric character:<tt>[\p{Alpha}\p{Digit}]</tt></td></tr>
172 * <tr><td valign="top" headers="construct posix"><tt>\p{Punct}</tt></td>
173 * <td headers="matches">Punctuation: One of <tt>!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~</tt></td></tr>
174 * <!-- <tt>[\!"#\$%&'\(\)\*\+,\-\./:;\<=\>\?@\[\\\]\^_`\{\|\}~]</tt>
175 * <tt>[\X21-\X2F\X31-\X40\X5B-\X60\X7B-\X7E]</tt> -->
176 * <tr><td valign="top" headers="construct posix"><tt>\p{Graph}</tt></td>
177 * <td headers="matches">A visible character: <tt>[\p{Alnum}\p{Punct}]</tt></td></tr>
178 * <tr><td valign="top" headers="construct posix"><tt>\p{Print}</tt></td>
179 * <td headers="matches">A printable character: <tt>[\p{Graph}\x20]</tt></td></tr>
180 * <tr><td valign="top" headers="construct posix"><tt>\p{Blank}</tt></td>
181 * <td headers="matches">A space or a tab: <tt>[ \t]</tt></td></tr>
182 * <tr><td valign="top" headers="construct posix"><tt>\p{Cntrl}</tt></td>
183 * <td headers="matches">A control character: <tt>[\x00-\x1F\x7F]</tt></td></tr>
184 * <tr><td valign="top" headers="construct posix"><tt>\p{XDigit}</tt></td>
185 * <td headers="matches">A hexadecimal digit: <tt>[0-9a-fA-F]</tt></td></tr>
186 * <tr><td valign="top" headers="construct posix"><tt>\p{Space}</tt></td>
187 * <td headers="matches">A whitespace character: <tt>[ \t\n\x0B\f\r]</tt></td></tr>
188 *
189 * <tr><th> </th></tr>
190 * <tr align="left"><th colspan="2">java.lang.Character classes (simple <a href="#jcc">java character type</a>)</th></tr>
191 *
192 * <tr><td valign="top"><tt>\p{javaLowerCase}</tt></td>
193 * <td>Equivalent to java.lang.Character.isLowerCase()</td></tr>
194 * <tr><td valign="top"><tt>\p{javaUpperCase}</tt></td>
195 * <td>Equivalent to java.lang.Character.isUpperCase()</td></tr>
196 * <tr><td valign="top"><tt>\p{javaWhitespace}</tt></td>
197 * <td>Equivalent to java.lang.Character.isWhitespace()</td></tr>
198 * <tr><td valign="top"><tt>\p{javaMirrored}</tt></td>
199 * <td>Equivalent to java.lang.Character.isMirrored()</td></tr>
200 *
201 * <tr><th> </th></tr>
202 * <tr align="left"><th colspan="2" id="unicode">Classes for Unicode blocks and categories</th></tr>
203 *
204 * <tr><td valign="top" headers="construct unicode"><tt>\p{InGreek}</tt></td>
205 * <td headers="matches">A character in the Greek block (simple <a href="#ubc">block</a>)</td></tr>
206 * <tr><td valign="top" headers="construct unicode"><tt>\p{Lu}</tt></td>
207 * <td headers="matches">An uppercase letter (simple <a href="#ubc">category</a>)</td></tr>
208 * <tr><td valign="top" headers="construct unicode"><tt>\p{Sc}</tt></td>
209 * <td headers="matches">A currency symbol</td></tr>
210 * <tr><td valign="top" headers="construct unicode"><tt>\P{InGreek}</tt></td>
211 * <td headers="matches">Any character except one in the Greek block (negation)</td></tr>
212 * <tr><td valign="top" headers="construct unicode"><tt>[\p{L}&&[^\p{Lu}]] </tt></td>
213 * <td headers="matches">Any letter except an uppercase letter (subtraction)</td></tr>
214 *
215 * <tr><th> </th></tr>
216 * <tr align="left"><th colspan="2" id="bounds">Boundary matchers</th></tr>
217 *
218 * <tr><td valign="top" headers="construct bounds"><tt>^</tt></td>
219 * <td headers="matches">The beginning of a line</td></tr>
220 * <tr><td valign="top" headers="construct bounds"><tt>$</tt></td>
221 * <td headers="matches">The end of a line</td></tr>
222 * <tr><td valign="top" headers="construct bounds"><tt>\b</tt></td>
223 * <td headers="matches">A word boundary</td></tr>
224 * <tr><td valign="top" headers="construct bounds"><tt>\B</tt></td>
225 * <td headers="matches">A non-word boundary</td></tr>
226 * <tr><td valign="top" headers="construct bounds"><tt>\A</tt></td>
227 * <td headers="matches">The beginning of the input</td></tr>
228 * <tr><td valign="top" headers="construct bounds"><tt>\G</tt></td>
229 * <td headers="matches">The end of the previous match</td></tr>
230 * <tr><td valign="top" headers="construct bounds"><tt>\Z</tt></td>
231 * <td headers="matches">The end of the input but for the final
232 * <a href="#lt">terminator</a>, if any</td></tr>
233 * <tr><td valign="top" headers="construct bounds"><tt>\z</tt></td>
234 * <td headers="matches">The end of the input</td></tr>
235 *
236 * <tr><th> </th></tr>
237 * <tr align="left"><th colspan="2" id="greedy">Greedy quantifiers</th></tr>
238 *
239 * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>?</tt></td>
240 * <td headers="matches"><i>X</i>, once or not at all</td></tr>
241 * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>*</tt></td>
242 * <td headers="matches"><i>X</i>, zero or more times</td></tr>
243 * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>+</tt></td>
244 * <td headers="matches"><i>X</i>, one or more times</td></tr>
245 * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>{</tt><i>n</i><tt>}</tt></td>
246 * <td headers="matches"><i>X</i>, exactly <i>n</i> times</td></tr>
247 * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>{</tt><i>n</i><tt>,}</tt></td>
248 * <td headers="matches"><i>X</i>, at least <i>n</i> times</td></tr>
249 * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>{</tt><i>n</i><tt>,</tt><i>m</i><tt>}</tt></td>
250 * <td headers="matches"><i>X</i>, at least <i>n</i> but not more than <i>m</i> times</td></tr>
251 *
252 * <tr><th> </th></tr>
253 * <tr align="left"><th colspan="2" id="reluc">Reluctant quantifiers</th></tr>
254 *
255 * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>??</tt></td>
256 * <td headers="matches"><i>X</i>, once or not at all</td></tr>
257 * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>*?</tt></td>
258 * <td headers="matches"><i>X</i>, zero or more times</td></tr>
259 * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>+?</tt></td>
260 * <td headers="matches"><i>X</i>, one or more times</td></tr>
261 * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>{</tt><i>n</i><tt>}?</tt></td>
262 * <td headers="matches"><i>X</i>, exactly <i>n</i> times</td></tr>
263 * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>{</tt><i>n</i><tt>,}?</tt></td>
264 * <td headers="matches"><i>X</i>, at least <i>n</i> times</td></tr>
265 * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>{</tt><i>n</i><tt>,</tt><i>m</i><tt>}?</tt></td>
266 * <td headers="matches"><i>X</i>, at least <i>n</i> but not more than <i>m</i> times</td></tr>
267 *
268 * <tr><th> </th></tr>
269 * <tr align="left"><th colspan="2" id="poss">Possessive quantifiers</th></tr>
270 *
271 * <tr><td valign="top" headers="construct poss"><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 poss"><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 poss"><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 poss"><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 poss"><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 poss"><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> </th></tr>
285 * <tr align="left"><th colspan="2" id="logical">Logical operators</th></tr>
286 *
287 * <tr><td valign="top" headers="construct logical"><i>XY</i></td>
288 * <td headers="matches"><i>X</i> followed by <i>Y</i></td></tr>
289 * <tr><td valign="top" headers="construct logical"><i>X</i><tt>|</tt><i>Y</i></td>
290 * <td headers="matches">Either <i>X</i> or <i>Y</i></td></tr>
291 * <tr><td valign="top" headers="construct logical"><tt>(</tt><i>X</i><tt>)</tt></td>
292 * <td headers="matches">X, as a <a href="#cg">capturing group</a></td></tr>
293 *
294 * <tr><th> </th></tr>
295 * <tr align="left"><th colspan="2" id="backref">Back references</th></tr>
296 *
297 * <tr><td valign="bottom" headers="construct backref"><tt>\</tt><i>n</i></td>
298 * <td valign="bottom" headers="matches">Whatever the <i>n</i><sup>th</sup>
299 * <a href="#cg">capturing group</a> matched</td></tr>
300 *
301 * <tr><th> </th></tr>
302 * <tr align="left"><th colspan="2" id="quot">Quotation</th></tr>
303 *
304 * <tr><td valign="top" headers="construct quot"><tt>\</tt></td>
305 * <td headers="matches">Nothing, but quotes the following character</td></tr>
306 * <tr><td valign="top" headers="construct quot"><tt>\Q</tt></td>
307 * <td headers="matches">Nothing, but quotes all characters until <tt>\E</tt></td></tr>
308 * <tr><td valign="top" headers="construct quot"><tt>\E</tt></td>
309 * <td headers="matches">Nothing, but ends quoting started by <tt>\Q</tt></td></tr>
310 * <!-- Metachars: !$()*+.<>?[\]^{|} -->
311 *
312 * <tr><th> </th></tr>
313 * <tr align="left"><th colspan="2" id="special">Special constructs (non-capturing)</th></tr>
314 *
315 * <tr><td valign="top" headers="construct special"><tt>(?:</tt><i>X</i><tt>)</tt></td>
316 * <td headers="matches"><i>X</i>, as a non-capturing group</td></tr>
317 * <tr><td valign="top" headers="construct special"><tt>(?idmsux-idmsux) </tt></td>
318 * <td headers="matches">Nothing, but turns match flags <a href="#CASE_INSENSITIVE">i</a>
319 * <a href="#UNIX_LINES">d</a> <a href="#MULTILINE">m</a> <a href="#DOTALL">s</a>
320 * <a href="#UNICODE_CASE">u</a> <a href="#COMMENTS">x</a> on - off</td></tr>
321 * <tr><td valign="top" headers="construct special"><tt>(?idmsux-idmsux:</tt><i>X</i><tt>)</tt> </td>
322 * <td headers="matches"><i>X</i>, as a <a href="#cg">non-capturing group</a> with the
323 * given flags <a href="#CASE_INSENSITIVE">i</a> <a href="#UNIX_LINES">d</a>
324 * <a href="#MULTILINE">m</a> <a href="#DOTALL">s</a> <a href="#UNICODE_CASE">u</a >
325 * <a href="#COMMENTS">x</a> on - off</td></tr>
326 * <tr><td valign="top" headers="construct special"><tt>(?=</tt><i>X</i><tt>)</tt></td>
327 * <td headers="matches"><i>X</i>, via zero-width positive lookahead</td></tr>
328 * <tr><td valign="top" headers="construct special"><tt>(?!</tt><i>X</i><tt>)</tt></td>
329 * <td headers="matches"><i>X</i>, via zero-width negative lookahead</td></tr>
330 * <tr><td valign="top" headers="construct special"><tt>(?<=</tt><i>X</i><tt>)</tt></td>
331 * <td headers="matches"><i>X</i>, via zero-width positive lookbehind</td></tr>
332 * <tr><td valign="top" headers="construct special"><tt>(?<!</tt><i>X</i><tt>)</tt></td>
333 * <td headers="matches"><i>X</i>, via zero-width negative lookbehind</td></tr>
334 * <tr><td valign="top" headers="construct special"><tt>(?></tt><i>X</i><tt>)</tt></td>
335 * <td headers="matches"><i>X</i>, as an independent, non-capturing group</td></tr>
336 *
337 * </table>
338 *
339 * <hr>
340 *
341 *
342 * <a name="bs">
343 * <h4> Backslashes, escapes, and quoting </h4>
344 *
345 * <p> The backslash character (<tt>'\'</tt>) serves to introduce escaped
346 * constructs, as defined in the table above, as well as to quote characters
347 * that otherwise would be interpreted as unescaped constructs. Thus the
348 * expression <tt>\\</tt> matches a single backslash and <tt>\{</tt> matches a
349 * left brace.
350 *
351 * <p> It is an error to use a backslash prior to any alphabetic character that
352 * does not denote an escaped construct; these are reserved for future
353 * extensions to the regular-expression language. A backslash may be used
354 * prior to a non-alphabetic character regardless of whether that character is
355 * part of an unescaped construct.
356 *
357 * <p> Backslashes within string literals in Java source code are interpreted
358 * as required by the <a
359 * href="http://java.sun.com/docs/books/jls">Java Language
360 * Specification</a> as either <a
361 * href="http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#100850">Unicode
362 * escapes</a> or other <a
363 * href="http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#101089">character
364 * escapes</a>. It is therefore necessary to double backslashes in string
365 * literals that represent regular expressions to protect them from
366 * interpretation by the Java bytecode compiler. The string literal
367 * <tt>"\b"</tt>, for example, matches a single backspace character when
368 * interpreted as a regular expression, while <tt>"\\b"</tt> matches a
369 * word boundary. The string literal <tt>"\(hello\)"</tt> is illegal
370 * and leads to a compile-time error; in order to match the string
371 * <tt>(hello)</tt> the string literal <tt>"\\(hello\\)"</tt>
372 * must be used.
373 *
374 * <a name="cc">
375 * <h4> Character Classes </h4>
376 *
377 * <p> Character classes may appear within other character classes, and
378 * may be composed by the union operator (implicit) and the intersection
379 * operator (<tt>&&</tt>).
380 * The union operator denotes a class that contains every character that is
381 * in at least one of its operand classes. The intersection operator
382 * denotes a class that contains every character that is in both of its
383 * operand classes.
384 *
385 * <p> The precedence of character-class operators is as follows, from
386 * highest to lowest:
387 *
388 * <blockquote><table border="0" cellpadding="1" cellspacing="0"
389 * summary="Precedence of character class operators.">
390 * <tr><th>1 </th>
391 * <td>Literal escape </td>
392 * <td><tt>\x</tt></td></tr>
393 * <tr><th>2 </th>
394 * <td>Grouping</td>
395 * <td><tt>[...]</tt></td></tr>
396 * <tr><th>3 </th>
397 * <td>Range</td>
398 * <td><tt>a-z</tt></td></tr>
399 * <tr><th>4 </th>
400 * <td>Union</td>
401 * <td><tt>[a-e][i-u]</tt></td></tr>
402 * <tr><th>5 </th>
403 * <td>Intersection</td>
404 * <td><tt>[a-z&&[aeiou]]</tt></td></tr>
405 * </table></blockquote>
406 *
407 * <p> Note that a different set of metacharacters are in effect inside
408 * a character class than outside a character class. For instance, the
409 * regular expression <tt>.</tt> loses its special meaning inside a
410 * character class, while the expression <tt>-</tt> becomes a range
411 * forming metacharacter.
412 *
413 * <a name="lt">
414 * <h4> Line terminators </h4>
415 *
416 * <p> A <i>line terminator</i> is a one- or two-character sequence that marks
417 * the end of a line of the input character sequence. The following are
418 * recognized as line terminators:
419 *
420 * <ul>
421 *
422 * <li> A newline (line feed) character (<tt>'\n'</tt>),
423 *
424 * <li> A carriage-return character followed immediately by a newline
425 * character (<tt>"\r\n"</tt>),
426 *
427 * <li> A standalone carriage-return character (<tt>'\r'</tt>),
428 *
429 * <li> A next-line character (<tt>'\u0085'</tt>),
430 *
431 * <li> A line-separator character (<tt>'\u2028'</tt>), or
432 *
433 * <li> A paragraph-separator character (<tt>'\u2029</tt>).
434 *
435 * </ul>
436 * <p>If {@link #UNIX_LINES} mode is activated, then the only line terminators
437 * recognized are newline characters.
438 *
439 * <p> The regular expression <tt>.</tt> matches any character except a line
440 * terminator unless the {@link #DOTALL} flag is specified.
441 *
442 * <p> By default, the regular expressions <tt>^</tt> and <tt>$</tt> ignore
443 * line terminators and only match at the beginning and the end, respectively,
444 * of the entire input sequence. If {@link #MULTILINE} mode is activated then
445 * <tt>^</tt> matches at the beginning of input and after any line terminator
446 * except at the end of input. When in {@link #MULTILINE} mode <tt>$</tt>
447 * matches just before a line terminator or the end of the input sequence.
448 *
449 * <a name="cg">
450 * <h4> Groups and capturing </h4>
451 *
452 * <p> Capturing groups are numbered by counting their opening parentheses from
453 * left to right. In the expression <tt>((A)(B(C)))</tt>, for example, there
454 * are four such groups: </p>
455 *
456 * <blockquote><table cellpadding=1 cellspacing=0 summary="Capturing group numberings">
457 * <tr><th>1 </th>
458 * <td><tt>((A)(B(C)))</tt></td></tr>
459 * <tr><th>2 </th>
460 * <td><tt>(A)</tt></td></tr>
461 * <tr><th>3 </th>
462 * <td><tt>(B(C))</tt></td></tr>
463 * <tr><th>4 </th>
464 * <td><tt>(C)</tt></td></tr>
465 * </table></blockquote>
466 *
467 * <p> Group zero always stands for the entire expression.
468 *
469 * <p> Capturing groups are so named because, during a match, each subsequence
470 * of the input sequence that matches such a group is saved. The captured
471 * subsequence may be used later in the expression, via a back reference, and
472 * may also be retrieved from the matcher once the match operation is complete.
473 *
474 * <p> The captured input associated with a group is always the subsequence
475 * that the group most recently matched. If a group is evaluated a second time
476 * because of quantification then its previously-captured value, if any, will
477 * be retained if the second evaluation fails. Matching the string
478 * <tt>"aba"</tt> against the expression <tt>(a(b)?)+</tt>, for example, leaves
479 * group two set to <tt>"b"</tt>. All captured input is discarded at the
480 * beginning of each match.
481 *
482 * <p> Groups beginning with <tt>(?</tt> are pure, <i>non-capturing</i> groups
483 * that do not capture text and do not count towards the group total.
484 *
485 *
486 * <h4> Unicode support </h4>
487 *
488 * <p> This class is in conformance with Level 1 of <a
489 * href="http://www.unicode.org/reports/tr18/"><i>Unicode Technical
490 * Standard #18: Unicode Regular Expression Guidelines</i></a>, plus RL2.1
491 * Canonical Equivalents.
492 *
493 * <p> Unicode escape sequences such as <tt>\u2014</tt> in Java source code
494 * are processed as described in <a
495 * href="http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#100850">\u00A73.3</a>
496 * of the Java Language Specification. Such escape sequences are also
497 * implemented directly by the regular-expression parser so that Unicode
498 * escapes can be used in expressions that are read from files or from the
499 * keyboard. Thus the strings <tt>"\u2014"</tt> and <tt>"\\u2014"</tt>,
500 * while not equal, compile into the same pattern, which matches the character
501 * with hexadecimal value <tt>0x2014</tt>.
502 *
503 * <a name="ubc"> <p>Unicode blocks and categories are written with the
504 * <tt>\p</tt> and <tt>\P</tt> constructs as in
505 * Perl. <tt>\p{</tt><i>prop</i><tt>}</tt> matches if the input has the
506 * property <i>prop</i>, while <tt>\P{</tt><i>prop</i><tt>}</tt> does not match if
507 * the input has that property. Blocks are specified with the prefix
508 * <tt>In</tt>, as in <tt>InMongolian</tt>. Categories may be specified with
509 * the optional prefix <tt>Is</tt>: Both <tt>\p{L}</tt> and <tt>\p{IsL}</tt>
510 * denote the category of Unicode letters. Blocks and categories can be used
511 * both inside and outside of a character class.
512 *
513 * <p> The supported categories are those of
514 * <a href="http://www.unicode.org/unicode/standard/standard.html">
515 * <i>The Unicode Standard</i></a> in the version specified by the
516 * {@link java.lang.Character Character} class. The category names are those
517 * defined in the Standard, both normative and informative.
518 * The block names supported by <code>Pattern</code> are the valid block names
519 * accepted and defined by
520 * {@link java.lang.Character.UnicodeBlock#forName(String) UnicodeBlock.forName}.
521 *
522 * <a name="jcc"> <p>Categories that behave like the java.lang.Character
523 * boolean is<i>methodname</i> methods (except for the deprecated ones) are
524 * available through the same <tt>\p{</tt><i>prop</i><tt>}</tt> syntax where
525 * the specified property has the name <tt>java<i>methodname</i></tt>.
526 *
527 * <h4> Comparison to Perl 5 </h4>
528 *
529 * <p>The <code>Pattern</code> engine performs traditional NFA-based matching
530 * with ordered alternation as occurs in Perl 5.
531 *
532 * <p> Perl constructs not supported by this class: </p>
533 *
534 * <ul>
535 *
536 * <li><p> The conditional constructs <tt>(?{</tt><i>X</i><tt>})</tt> and
537 * <tt>(?(</tt><i>condition</i><tt>)</tt><i>X</i><tt>|</tt><i>Y</i><tt>)</tt>,
538 * </p></li>
539 *
540 * <li><p> The embedded code constructs <tt>(?{</tt><i>code</i><tt>})</tt>
541 * and <tt>(??{</tt><i>code</i><tt>})</tt>,</p></li>
542 *
543 * <li><p> The embedded comment syntax <tt>(?#comment)</tt>, and </p></li>
544 *
545 * <li><p> The preprocessing operations <tt>\l</tt> <tt>\u</tt>,
546 * <tt>\L</tt>, and <tt>\U</tt>. </p></li>
547 *
548 * </ul>
549 *
550 * <p> Constructs supported by this class but not by Perl: </p>
551 *
552 * <ul>
553 *
554 * <li><p> Possessive quantifiers, which greedily match as much as they can
555 * and do not back off, even when doing so would allow the overall match to
556 * succeed. </p></li>
557 *
558 * <li><p> Character-class union and intersection as described
559 * <a href="#cc">above</a>.</p></li>
560 *
561 * </ul>
562 *
563 * <p> Notable differences from Perl: </p>
564 *
565 * <ul>
566 *
567 * <li><p> In Perl, <tt>\1</tt> through <tt>\9</tt> are always interpreted
568 * as back references; a backslash-escaped number greater than <tt>9</tt> is
569 * treated as a back reference if at least that many subexpressions exist,
570 * otherwise it is interpreted, if possible, as an octal escape. In this
571 * class octal escapes must always begin with a zero. In this class,
572 * <tt>\1</tt> through <tt>\9</tt> are always interpreted as back
573 * references, and a larger number is accepted as a back reference if at
574 * least that many subexpressions exist at that point in the regular
575 * expression, otherwise the parser will drop digits until the number is
576 * smaller or equal to the existing number of groups or it is one digit.
577 * </p></li>
578 *
579 * <li><p> Perl uses the <tt>g</tt> flag to request a match that resumes
580 * where the last match left off. This functionality is provided implicitly
581 * by the {@link Matcher} class: Repeated invocations of the {@link
582 * Matcher#find find} method will resume where the last match left off,
583 * unless the matcher is reset. </p></li>
584 *
585 * <li><p> In Perl, embedded flags at the top level of an expression affect
586 * the whole expression. In this class, embedded flags always take effect
587 * at the point at which they appear, whether they are at the top level or
588 * within a group; in the latter case, flags are restored at the end of the
589 * group just as in Perl. </p></li>
590 *
591 * <li><p> Perl is forgiving about malformed matching constructs, as in the
592 * expression <tt>*a</tt>, as well as dangling brackets, as in the
593 * expression <tt>abc]</tt>, and treats them as literals. This
594 * class also accepts dangling brackets but is strict about dangling
595 * metacharacters like +, ? and *, and will throw a
596 * {@link PatternSyntaxException} if it encounters them. </p></li>
597 *
598 * </ul>
599 *
600 *
601 * <p> For a more precise description of the behavior of regular expression
602 * constructs, please see <a href="http://www.oreilly.com/catalog/regex3/">
603 * <i>Mastering Regular Expressions, 3nd Edition</i>, Jeffrey E. F. Friedl,
604 * O'Reilly and Associates, 2006.</a>
605 * </p>
606 *
607 * @see java.lang.String#split(String, int)
608 * @see java.lang.String#split(String)
609 *
610 * @author Mike McCloskey
611 * @author Mark Reinhold
612 * @author JSR-51 Expert Group
613 * @since 1.4
614 * @spec JSR-51
615 */
616
617 public final class Pattern
618 implements java.io.Serializable
619 {
620
621 /**
622 * Regular expression modifier values. Instead of being passed as
623 * arguments, they can also be passed as inline modifiers.
624 * For example, the following statements have the same effect.
625 * <pre>
626 * RegExp r1 = RegExp.compile("abc", Pattern.I|Pattern.M);
627 * RegExp r2 = RegExp.compile("(?im)abc", 0);
628 * </pre>
629 *
630 * The flags are duplicated so that the familiar Perl match flag
631 * names are available.
632 */
633
634 /**
635 * Enables Unix lines mode.
636 *
637 * <p> In this mode, only the <tt>'\n'</tt> line terminator is recognized
638 * in the behavior of <tt>.</tt>, <tt>^</tt>, and <tt>$</tt>.
639 *
640 * <p> Unix lines mode can also be enabled via the embedded flag
641 * expression <tt>(?d)</tt>.
642 */
643 public static final int UNIX_LINES = 0x01;
644
645 /**
646 * Enables case-insensitive matching.
647 *
648 * <p> By default, case-insensitive matching assumes that only characters
649 * in the US-ASCII charset are being matched. Unicode-aware
650 * case-insensitive matching can be enabled by specifying the {@link
651 * #UNICODE_CASE} flag in conjunction with this flag.
652 *
653 * <p> Case-insensitive matching can also be enabled via the embedded flag
654 * expression <tt>(?i)</tt>.
655 *
656 * <p> Specifying this flag may impose a slight performance penalty. </p>
657 */
658 public static final int CASE_INSENSITIVE = 0x02;
659
660 /**
661 * Permits whitespace and comments in pattern.
662 *
663 * <p> In this mode, whitespace is ignored, and embedded comments starting
664 * with <tt>#</tt> are ignored until the end of a line.
665 *
666 * <p> Comments mode can also be enabled via the embedded flag
667 * expression <tt>(?x)</tt>.
668 */
669 public static final int COMMENTS = 0x04;
670
671 /**
672 * Enables multiline mode.
673 *
674 * <p> In multiline mode the expressions <tt>^</tt> and <tt>$</tt> match
675 * just after or just before, respectively, a line terminator or the end of
676 * the input sequence. By default these expressions only match at the
677 * beginning and the end of the entire input sequence.
678 *
679 * <p> Multiline mode can also be enabled via the embedded flag
680 * expression <tt>(?m)</tt>. </p>
681 */
682 public static final int MULTILINE = 0x08;
683
684 /**
685 * Enables literal parsing of the pattern.
686 *
687 * <p> When this flag is specified then the input string that specifies
688 * the pattern is treated as a sequence of literal characters.
689 * Metacharacters or escape sequences in the input sequence will be
690 * given no special meaning.
691 *
692 * <p>The flags CASE_INSENSITIVE and UNICODE_CASE retain their impact on
693 * matching when used in conjunction with this flag. The other flags
694 * become superfluous.
695 *
696 * <p> There is no embedded flag character for enabling literal parsing.
697 * @since 1.5
698 */
699 public static final int LITERAL = 0x10;
700
701 /**
702 * Enables dotall mode.
703 *
704 * <p> In dotall mode, the expression <tt>.</tt> matches any character,
705 * including a line terminator. By default this expression does not match
706 * line terminators.
707 *
708 * <p> Dotall mode can also be enabled via the embedded flag
709 * expression <tt>(?s)</tt>. (The <tt>s</tt> is a mnemonic for
710 * "single-line" mode, which is what this is called in Perl.) </p>
711 */
712 public static final int DOTALL = 0x20;
713
714 /**
715 * Enables Unicode-aware case folding.
716 *
717 * <p> When this flag is specified then case-insensitive matching, when
718 * enabled by the {@link #CASE_INSENSITIVE} flag, is done in a manner
719 * consistent with the Unicode Standard. By default, case-insensitive
720 * matching assumes that only characters in the US-ASCII charset are being
721 * matched.
722 *
723 * <p> Unicode-aware case folding can also be enabled via the embedded flag
724 * expression <tt>(?u)</tt>.
725 *
726 * <p> Specifying this flag may impose a performance penalty. </p>
727 */
728 public static final int UNICODE_CASE = 0x40;
729
730 /**
731 * Enables canonical equivalence.
732 *
733 * <p> When this flag is specified then two characters will be considered
734 * to match if, and only if, their full canonical decompositions match.
735 * The expression <tt>"a\u030A"</tt>, for example, will match the
736 * string <tt>"\u00E5"</tt> when this flag is specified. By default,
737 * matching does not take canonical equivalence into account.
738 *
739 * <p> There is no embedded flag character for enabling canonical
740 * equivalence.
741 *
742 * <p> Specifying this flag may impose a performance penalty. </p>
743 */
744 public static final int CANON_EQ = 0x80;
745
746 /* Pattern has only two serialized components: The pattern string
747 * and the flags, which are all that is needed to recompile the pattern
748 * when it is deserialized.
749 */
750
751 /** use serialVersionUID from Merlin b59 for interoperability */
752 private static final long serialVersionUID = 5073258162644648461L;
753
754 /**
755 * The original regular-expression pattern string.
756 *
757 * @serial
758 */
759 private String pattern;
760
761 /**
762 * The original pattern flags.
763 *
764 * @serial
765 */
766 private int flags;
767
768 /**
769 * Boolean indicating this Pattern is compiled; this is necessary in order
770 * to lazily compile deserialized Patterns.
771 */
772 private transient volatile boolean compiled = false;
773
774 /**
775 * The normalized pattern string.
776 */
777 private transient String normalizedPattern;
778
779 /**
780 * The starting point of state machine for the find operation. This allows
781 * a match to start anywhere in the input.
782 */
783 transient Node root;
784
785 /**
786 * The root of object tree for a match operation. The pattern is matched
787 * at the beginning. This may include a find that uses BnM or a First
788 * node.
789 */
790 transient Node matchRoot;
791
792 /**
793 * Temporary storage used by parsing pattern slice.
794 */
795 transient int[] buffer;
796
797 /**
798 * Temporary storage used while parsing group references.
799 */
800 transient GroupHead[] groupNodes;
801
802 /**
803 * Temporary null terminated code point array used by pattern compiling.
804 */
805 private transient int[] temp;
806
807 /**
808 * The number of capturing groups in this Pattern. Used by matchers to
809 * allocate storage needed to perform a match.
810 */
811 transient int capturingGroupCount;
812
813 /**
814 * The local variable count used by parsing tree. Used by matchers to
815 * allocate storage needed to perform a match.
816 */
817 transient int localCount;
818
819 /**
820 * Index into the pattern string that keeps track of how much has been
821 * parsed.
822 */
823 private transient int cursor;
824
825 /**
826 * Holds the length of the pattern string.
827 */
828 private transient int patternLength;
829
830 /**
831 * Compiles the given regular expression into a pattern. </p>
832 *
833 * @param regex
834 * The expression to be compiled
835 *
836 * @throws PatternSyntaxException
837 * If the expression's syntax is invalid
838 */
839 public static Pattern compile(String regex) {
840 return new Pattern(regex, 0);
841 }
842
843 /**
844 * Compiles the given regular expression into a pattern with the given
845 * flags. </p>
846 *
847 * @param regex
848 * The expression to be compiled
849 *
850 * @param flags
851 * Match flags, a bit mask that may include
852 * {@link #CASE_INSENSITIVE}, {@link #MULTILINE}, {@link #DOTALL},
853 * {@link #UNICODE_CASE}, {@link #CANON_EQ}, {@link #UNIX_LINES},
854 * {@link #LITERAL} and {@link #COMMENTS}
855 *
856 * @throws IllegalArgumentException
857 * If bit values other than those corresponding to the defined
858 * match flags are set in <tt>flags</tt>
859 *
860 * @throws PatternSyntaxException
861 * If the expression's syntax is invalid
862 */
863 public static Pattern compile(String regex, int flags) {
864 return new Pattern(regex, flags);
865 }
866
867 /**
868 * Returns the regular expression from which this pattern was compiled.
869 * </p>
870 *
871 * @return The source of this pattern
872 */
873 public String pattern() {
874 return pattern;
875 }
876
877 /**
878 * <p>Returns the string representation of this pattern. This
879 * is the regular expression from which this pattern was
880 * compiled.</p>
881 *
882 * @return The string representation of this pattern
883 * @since 1.5
884 */
885 public String toString() {
886 return pattern;
887 }
888
889 /**
890 * Creates a matcher that will match the given input against this pattern.
891 * </p>
892 *
893 * @param input
894 * The character sequence to be matched
895 *
896 * @return A new matcher for this pattern
897 */
898 public Matcher matcher(CharSequence input) {
899 if (!compiled) {
900 synchronized(this) {
901 if (!compiled)
902 compile();
903 }
904 }
905 Matcher m = new Matcher(this, input);
906 return m;
907 }
908
909 /**
910 * Returns this pattern's match flags. </p>
911 *
912 * @return The match flags specified when this pattern was compiled
913 */
914 public int flags() {
915 return flags;
916 }
917
918 /**
919 * Compiles the given regular expression and attempts to match the given
920 * input against it.
921 *
922 * <p> An invocation of this convenience method of the form
923 *
924 * <blockquote><pre>
925 * Pattern.matches(regex, input);</pre></blockquote>
926 *
927 * behaves in exactly the same way as the expression
928 *
929 * <blockquote><pre>
930 * Pattern.compile(regex).matcher(input).matches()</pre></blockquote>
931 *
932 * <p> If a pattern is to be used multiple times, compiling it once and reusing
933 * it will be more efficient than invoking this method each time. </p>
934 *
935 * @param regex
936 * The expression to be compiled
937 *
938 * @param input
939 * The character sequence to be matched
940 *
941 * @throws PatternSyntaxException
942 * If the expression's syntax is invalid
943 */
944 public static boolean matches(String regex, CharSequence input) {
945 Pattern p = Pattern.compile(regex);
946 Matcher m = p.matcher(input);
947 return m.matches();
948 }
949
950 /**
951 * Splits the given input sequence around matches of this pattern.
952 *
953 * <p> The array returned by this method contains each substring of the
954 * input sequence that is terminated by another subsequence that matches
955 * this pattern or is terminated by the end of the input sequence. The
956 * substrings in the array are in the order in which they occur in the
957 * input. If this pattern does not match any subsequence of the input then
958 * the resulting array has just one element, namely the input sequence in
959 * string form.
960 *
961 * <p> The <tt>limit</tt> parameter controls the number of times the
962 * pattern is applied and therefore affects the length of the resulting
963 * array. If the limit <i>n</i> is greater than zero then the pattern
964 * will be applied at most <i>n</i> - 1 times, the array's
965 * length will be no greater than <i>n</i>, and the array's last entry
966 * will contain all input beyond the last matched delimiter. If <i>n</i>
967 * is non-positive then the pattern will be applied as many times as
968 * possible and the array can have any length. If <i>n</i> is zero then
969 * the pattern will be applied as many times as possible, the array can
970 * have any length, and trailing empty strings will be discarded.
971 *
972 * <p> The input <tt>"boo:and:foo"</tt>, for example, yields the following
973 * results with these parameters:
974 *
975 * <blockquote><table cellpadding=1 cellspacing=0
976 * summary="Split examples showing regex, limit, and result">
977 * <tr><th><P align="left"><i>Regex </i></th>
978 * <th><P align="left"><i>Limit </i></th>
979 * <th><P align="left"><i>Result </i></th></tr>
980 * <tr><td align=center>:</td>
981 * <td align=center>2</td>
982 * <td><tt>{ "boo", "and:foo" }</tt></td></tr>
983 * <tr><td align=center>:</td>
984 * <td align=center>5</td>
985 * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
986 * <tr><td align=center>:</td>
987 * <td align=center>-2</td>
988 * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
989 * <tr><td align=center>o</td>
990 * <td align=center>5</td>
991 * <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
992 * <tr><td align=center>o</td>
993 * <td align=center>-2</td>
994 * <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
995 * <tr><td align=center>o</td>
996 * <td align=center>0</td>
997 * <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
998 * </table></blockquote>
999 *
1000 *
1001 * @param input
1002 * The character sequence to be split
1003 *
1004 * @param limit
1005 * The result threshold, as described above
1006 *
1007 * @return The array of strings computed by splitting the input
1008 * around matches of this pattern
1009 */
1010 public String[] split(CharSequence input, int limit) {
1011 int index = 0;
1012 boolean matchLimited = limit > 0;
1013 ArrayList<String> matchList = new ArrayList<String>();
1014 Matcher m = matcher(input);
1015
1016 // Add segments before each match found
1017 while(m.find()) {
1018 if (!matchLimited || matchList.size() < limit - 1) {
1019 String match = input.subSequence(index, m.start()).toString();
1020 matchList.add(match);
1021 index = m.end();
1022 } else if (matchList.size() == limit - 1) { // last one
1023 String match = input.subSequence(index,
1024 input.length()).toString();
1025 matchList.add(match);
1026 index = m.end();
1027 }
1028 }
1029
1030 // If no match was found, return this
1031 if (index == 0)
1032 return new String[] {input.toString()};
1033
1034 // Add remaining segment
1035 if (!matchLimited || matchList.size() < limit)
1036 matchList.add(input.subSequence(index, input.length()).toString());
1037
1038 // Construct result
1039 int resultSize = matchList.size();
1040 if (limit == 0)
1041 while (resultSize > 0 && matchList.get(resultSize-1).equals(""))
1042 resultSize--;
1043 String[] result = new String[resultSize];
1044 return matchList.subList(0, resultSize).toArray(result);
1045 }
1046
1047 /**
1048 * Splits the given input sequence around matches of this pattern.
1049 *
1050 * <p> This method works as if by invoking the two-argument {@link
1051 * #split(java.lang.CharSequence, int) split} method with the given input
1052 * sequence and a limit argument of zero. Trailing empty strings are
1053 * therefore not included in the resulting array. </p>
1054 *
1055 * <p> The input <tt>"boo:and:foo"</tt>, for example, yields the following
1056 * results with these expressions:
1057 *
1058 * <blockquote><table cellpadding=1 cellspacing=0
1059 * summary="Split examples showing regex and result">
1060 * <tr><th><P align="left"><i>Regex </i></th>
1061 * <th><P align="left"><i>Result</i></th></tr>
1062 * <tr><td align=center>:</td>
1063 * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
1064 * <tr><td align=center>o</td>
1065 * <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
1066 * </table></blockquote>
1067 *
1068 *
1069 * @param input
1070 * The character sequence to be split
1071 *
1072 * @return The array of strings computed by splitting the input
1073 * around matches of this pattern
1074 */
1075 public String[] split(CharSequence input) {
1076 return split(input, 0);
1077 }
1078
1079 /**
1080 * Returns a literal pattern <code>String</code> for the specified
1081 * <code>String</code>.
1082 *
1083 * <p>This method produces a <code>String</code> that can be used to
1084 * create a <code>Pattern</code> that would match the string
1085 * <code>s</code> as if it were a literal pattern.</p> Metacharacters
1086 * or escape sequences in the input sequence will be given no special
1087 * meaning.
1088 *
1089 * @param s The string to be literalized
1090 * @return A literal string replacement
1091 * @since 1.5
1092 */
1093 public static String quote(String s) {
1094 int slashEIndex = s.indexOf("\\E");
1095 if (slashEIndex == -1)
1096 return "\\Q" + s + "\\E";
1097
1098 StringBuilder sb = new StringBuilder(s.length() * 2);
1099 sb.append("\\Q");
1100 slashEIndex = 0;
1101 int current = 0;
1102 while ((slashEIndex = s.indexOf("\\E", current)) != -1) {
1103 sb.append(s.substring(current, slashEIndex));
1104 current = slashEIndex + 2;
1105 sb.append("\\E\\\\E\\Q");
1106 }
1107 sb.append(s.substring(current, s.length()));
1108 sb.append("\\E");
1109 return sb.toString();
1110 }
1111
1112 /**
1113 * Recompile the Pattern instance from a stream. The original pattern
1114 * string is read in and the object tree is recompiled from it.
1115 */
1116 private void readObject(java.io.ObjectInputStream s)
1117 throws java.io.IOException, ClassNotFoundException {
1118
1119 // Read in all fields
1120 s.defaultReadObject();
1121
1122 // Initialize counts
1123 capturingGroupCount = 1;
1124 localCount = 0;
1125
1126 // if length > 0, the Pattern is lazily compiled
1127 compiled = false;
1128 if (pattern.length() == 0) {
1129 root = new Start(lastAccept);
1130 matchRoot = lastAccept;
1131 compiled = true;
1132 }
1133 }
1134
1135 /**
1136 * This private constructor is used to create all Patterns. The pattern
1137 * string and match flags are all that is needed to completely describe
1138 * a Pattern. An empty pattern string results in an object tree with
1139 * only a Start node and a LastNode node.
1140 */
1141 private Pattern(String p, int f) {
1142 pattern = p;
1143 flags = f;
1144
1145 // Reset group index count
1146 capturingGroupCount = 1;
1147 localCount = 0;
1148
1149 if (pattern.length() > 0) {
1150 compile();
1151 } else {
1152 root = new Start(lastAccept);
1153 matchRoot = lastAccept;
1154 }
1155 }
1156
1157 /**
1158 * The pattern is converted to normalizedD form and then a pure group
1159 * is constructed to match canonical equivalences of the characters.
1160 */
1161 private void normalize() {
1162 boolean inCharClass = false;
1163 int lastCodePoint = -1;
1164
1165 // Convert pattern into normalizedD form
1166 normalizedPattern = Normalizer.normalize(pattern, Normalizer.Form.NFD);
1167 patternLength = normalizedPattern.length();
1168
1169 // Modify pattern to match canonical equivalences
1170 StringBuilder newPattern = new StringBuilder(patternLength);
1171 for(int i=0; i<patternLength; ) {
1172 int c = normalizedPattern.codePointAt(i);
1173 StringBuilder sequenceBuffer;
1174 if ((Character.getType(c) == Character.NON_SPACING_MARK)
1175 && (lastCodePoint != -1)) {
1176 sequenceBuffer = new StringBuilder();
1177 sequenceBuffer.appendCodePoint(lastCodePoint);
1178 sequenceBuffer.appendCodePoint(c);
1179 while(Character.getType(c) == Character.NON_SPACING_MARK) {
1180 i += Character.charCount(c);
1181 if (i >= patternLength)
1182 break;
1183 c = normalizedPattern.codePointAt(i);
1184 sequenceBuffer.appendCodePoint(c);
1185 }
1186 String ea = produceEquivalentAlternation(
1187 sequenceBuffer.toString());
1188 newPattern.setLength(newPattern.length()-Character.charCount(lastCodePoint));
1189 newPattern.append("(?:").append(ea).append(")");
1190 } else if (c == '[' && lastCodePoint != '\\') {
1191 i = normalizeCharClass(newPattern, i);
1192 } else {
1193 newPattern.appendCodePoint(c);
1194 }
1195 lastCodePoint = c;
1196 i += Character.charCount(c);
1197 }
1198 normalizedPattern = newPattern.toString();
1199 }
1200
1201 /**
1202 * Complete the character class being parsed and add a set
1203 * of alternations to it that will match the canonical equivalences
1204 * of the characters within the class.
1205 */
1206 private int normalizeCharClass(StringBuilder newPattern, int i) {
1207 StringBuilder charClass = new StringBuilder();
1208 StringBuilder eq = null;
1209 int lastCodePoint = -1;
1210 String result;
1211
1212 i++;
1213 charClass.append("[");
1214 while(true) {
1215 int c = normalizedPattern.codePointAt(i);
1216 StringBuilder sequenceBuffer;
1217
1218 if (c == ']' && lastCodePoint != '\\') {
1219 charClass.append((char)c);
1220 break;
1221 } else if (Character.getType(c) == Character.NON_SPACING_MARK) {
1222 sequenceBuffer = new StringBuilder();
1223 sequenceBuffer.appendCodePoint(lastCodePoint);
1224 while(Character.getType(c) == Character.NON_SPACING_MARK) {
1225 sequenceBuffer.appendCodePoint(c);
1226 i += Character.charCount(c);
1227 if (i >= normalizedPattern.length())
1228 break;
1229 c = normalizedPattern.codePointAt(i);
1230 }
1231 String ea = produceEquivalentAlternation(
1232 sequenceBuffer.toString());
1233
1234 charClass.setLength(charClass.length()-Character.charCount(lastCodePoint));
1235 if (eq == null)
1236 eq = new StringBuilder();
1237 eq.append('|');
1238 eq.append(ea);
1239 } else {
1240 charClass.appendCodePoint(c);
1241 i++;
1242 }
1243 if (i == normalizedPattern.length())
1244 throw error("Unclosed character class");
1245 lastCodePoint = c;
1246 }
1247
1248 if (eq != null) {
1249 result = "(?:"+charClass.toString()+eq.toString()+")";
1250 } else {
1251 result = charClass.toString();
1252 }
1253
1254 newPattern.append(result);
1255 return i;
1256 }
1257
1258 /**
1259 * Given a specific sequence composed of a regular character and
1260 * combining marks that follow it, produce the alternation that will
1261 * match all canonical equivalences of that sequence.
1262 */
1263 private String produceEquivalentAlternation(String source) {
1264 int len = countChars(source, 0, 1);
1265 if (source.length() == len)
1266 // source has one character.
1267 return source;
1268
1269 String base = source.substring(0,len);
1270 String combiningMarks = source.substring(len);
1271
1272 String[] perms = producePermutations(combiningMarks);
1273 StringBuilder result = new StringBuilder(source);
1274
1275 // Add combined permutations
1276 for(int x=0; x<perms.length; x++) {
1277 String next = base + perms[x];
1278 if (x>0)
1279 result.append("|"+next);
1280 next = composeOneStep(next);
1281 if (next != null)
1282 result.append("|"+produceEquivalentAlternation(next));
1283 }
1284 return result.toString();
1285 }
1286
1287 /**
1288 * Returns an array of strings that have all the possible
1289 * permutations of the characters in the input string.
1290 * This is used to get a list of all possible orderings
1291 * of a set of combining marks. Note that some of the permutations
1292 * are invalid because of combining class collisions, and these
1293 * possibilities must be removed because they are not canonically
1294 * equivalent.
1295 */
1296 private String[] producePermutations(String input) {
1297 if (input.length() == countChars(input, 0, 1))
1298 return new String[] {input};
1299
1300 if (input.length() == countChars(input, 0, 2)) {
1301 int c0 = Character.codePointAt(input, 0);
1302 int c1 = Character.codePointAt(input, Character.charCount(c0));
1303 if (getClass(c1) == getClass(c0)) {
1304 return new String[] {input};
1305 }
1306 String[] result = new String[2];
1307 result[0] = input;
1308 StringBuilder sb = new StringBuilder(2);
1309 sb.appendCodePoint(c1);
1310 sb.appendCodePoint(c0);
1311 result[1] = sb.toString();
1312 return result;
1313 }
1314
1315 int length = 1;
1316 int nCodePoints = countCodePoints(input);
1317 for(int x=1; x<nCodePoints; x++)
1318 length = length * (x+1);
1319
1320 String[] temp = new String[length];
1321
1322 int combClass[] = new int[nCodePoints];
1323 for(int x=0, i=0; x<nCodePoints; x++) {
1324 int c = Character.codePointAt(input, i);
1325 combClass[x] = getClass(c);
1326 i += Character.charCount(c);
1327 }
1328
1329 // For each char, take it out and add the permutations
1330 // of the remaining chars
1331 int index = 0;
1332 int len;
1333 // offset maintains the index in code units.
1334 loop: for(int x=0, offset=0; x<nCodePoints; x++, offset+=len) {
1335 len = countChars(input, offset, 1);
1336 boolean skip = false;
1337 for(int y=x-1; y>=0; y--) {
1338 if (combClass[y] == combClass[x]) {
1339 continue loop;
1340 }
1341 }
1342 StringBuilder sb = new StringBuilder(input);
1343 String otherChars = sb.delete(offset, offset+len).toString();
1344 String[] subResult = producePermutations(otherChars);
1345
1346 String prefix = input.substring(offset, offset+len);
1347 for(int y=0; y<subResult.length; y++)
1348 temp[index++] = prefix + subResult[y];
1349 }
1350 String[] result = new String[index];
1351 for (int x=0; x<index; x++)
1352 result[x] = temp[x];
1353 return result;
1354 }
1355
1356 private int getClass(int c) {
1357 return sun.text.Normalizer.getCombiningClass(c);
1358 }
1359
1360 /**
1361 * Attempts to compose input by combining the first character
1362 * with the first combining mark following it. Returns a String
1363 * that is the composition of the leading character with its first
1364 * combining mark followed by the remaining combining marks. Returns
1365 * null if the first two characters cannot be further composed.
1366 */
1367 private String composeOneStep(String input) {
1368 int len = countChars(input, 0, 2);
1369 String firstTwoCharacters = input.substring(0, len);
1370 String result = Normalizer.normalize(firstTwoCharacters, Normalizer.Form.NFC);
1371
1372 if (result.equals(firstTwoCharacters))
1373 return null;
1374 else {
1375 String remainder = input.substring(len);
1376 return result + remainder;
1377 }
1378 }
1379
1380 /**
1381 * Preprocess any \Q...\E sequences in `temp', meta-quoting them.
1382 * See the description of `quotemeta' in perlfunc(1).
1383 */
1384 private void RemoveQEQuoting() {
1385 final int pLen = patternLength;
1386 int i = 0;
1387 while (i < pLen-1) {
1388 if (temp[i] != '\\')
1389 i += 1;
1390 else if (temp[i + 1] != 'Q')
1391 i += 2;
1392 else
1393 break;
1394 }
1395 if (i >= pLen - 1) // No \Q sequence found
1396 return;
1397 int j = i;
1398 i += 2;
1399 int[] newtemp = new int[j + 2*(pLen-i) + 2];
1400 System.arraycopy(temp, 0, newtemp, 0, j);
1401
1402 boolean inQuote = true;
1403 while (i < pLen) {
1404 int c = temp[i++];
1405 if (! ASCII.isAscii(c) || ASCII.isAlnum(c)) {
1406 newtemp[j++] = c;
1407 } else if (c != '\\') {
1408 if (inQuote) newtemp[j++] = '\\';
1409 newtemp[j++] = c;
1410 } else if (inQuote) {
1411 if (temp[i] == 'E') {
1412 i++;
1413 inQuote = false;
1414 } else {
1415 newtemp[j++] = '\\';
1416 newtemp[j++] = '\\';
1417 }
1418 } else {
1419 if (temp[i] == 'Q') {
1420 i++;
1421 inQuote = true;
1422 } else {
1423 newtemp[j++] = c;
1424 if (i != pLen)
1425 newtemp[j++] = temp[i++];
1426 }
1427 }
1428 }
1429
1430 patternLength = j;
1431 temp = Arrays.copyOf(newtemp, j + 2); // double zero termination
1432 }
1433
1434 /**
1435 * Copies regular expression to an int array and invokes the parsing
1436 * of the expression which will create the object tree.
1437 */
1438 private void compile() {
1439 // Handle canonical equivalences
1440 if (has(CANON_EQ) && !has(LITERAL)) {
1441 normalize();
1442 } else {
1443 normalizedPattern = pattern;
1444 }
1445 patternLength = normalizedPattern.length();
1446
1447 // Copy pattern to int array for convenience
1448 // Use double zero to terminate pattern
1449 temp = new int[patternLength + 2];
1450
1451 boolean hasSupplementary = false;
1452 int c, count = 0;
1453 // Convert all chars into code points
1454 for (int x = 0; x < patternLength; x += Character.charCount(c)) {
1455 c = normalizedPattern.codePointAt(x);
1456 if (isSupplementary(c)) {
1457 hasSupplementary = true;
1458 }
1459 temp[count++] = c;
1460 }
1461
1462 patternLength = count; // patternLength now in code points
1463
1464 if (! has(LITERAL))
1465 RemoveQEQuoting();
1466
1467 // Allocate all temporary objects here.
1468 buffer = new int[32];
1469 groupNodes = new GroupHead[10];
1470
1471 if (has(LITERAL)) {
1472 // Literal pattern handling
1473 matchRoot = newSlice(temp, patternLength, hasSupplementary);
1474 matchRoot.next = lastAccept;
1475 } else {
1476 // Start recursive descent parsing
1477 matchRoot = expr(lastAccept);
1478 // Check extra pattern characters
1479 if (patternLength != cursor) {
1480 if (peek() == ')') {
1481 throw error("Unmatched closing ')'");
1482 } else {
1483 throw error("Unexpected internal error");
1484 }
1485 }
1486 }
1487
1488 // Peephole optimization
1489 if (matchRoot instanceof Slice) {
1490 root = BnM.optimize(matchRoot);
1491 if (root == matchRoot) {
1492 root = hasSupplementary ? new StartS(matchRoot) : new Start(matchRoot);
1493 }
1494 } else if (matchRoot instanceof Begin || matchRoot instanceof First) {
1495 root = matchRoot;
1496 } else {
1497 root = hasSupplementary ? new StartS(matchRoot) : new Start(matchRoot);
1498 }
1499
1500 // Release temporary storage
1501 temp = null;
1502 buffer = null;
1503 groupNodes = null;
1504 patternLength = 0;
1505 compiled = true;
1506 }
1507
1508 /**
1509 * Used to print out a subtree of the Pattern to help with debugging.
1510 */
1511 private static void printObjectTree(Node node) {
1512 while(node != null) {
1513 if (node instanceof Prolog) {
1514 System.out.println(node);
1515 printObjectTree(((Prolog)node).loop);
1516 System.out.println("**** end contents prolog loop");
1517 } else if (node instanceof Loop) {
1518 System.out.println(node);
1519 printObjectTree(((Loop)node).body);
1520 System.out.println("**** end contents Loop body");
1521 } else if (node instanceof Curly) {
1522 System.out.println(node);
1523 printObjectTree(((Curly)node).atom);
1524 System.out.println("**** end contents Curly body");
1525 } else if (node instanceof GroupCurly) {
1526 System.out.println(node);
1527 printObjectTree(((GroupCurly)node).atom);
1528 System.out.println("**** end contents GroupCurly body");
1529 } else if (node instanceof GroupTail) {
1530 System.out.println(node);
1531 System.out.println("Tail next is "+node.next);
1532 return;
1533 } else {
1534 System.out.println(node);
1535 }
1536 node = node.next;
1537 if (node != null)
1538 System.out.println("->next:");
1539 if (node == Pattern.accept) {
1540 System.out.println("Accept Node");
1541 node = null;
1542 }
1543 }
1544 }
1545
1546 /**
1547 * Used to accumulate information about a subtree of the object graph
1548 * so that optimizations can be applied to the subtree.
1549 */
1550 static final class TreeInfo {
1551 int minLength;
1552 int maxLength;
1553 boolean maxValid;
1554 boolean deterministic;
1555
1556 TreeInfo() {
1557 reset();
1558 }
1559 void reset() {
1560 minLength = 0;
1561 maxLength = 0;
1562 maxValid = true;
1563 deterministic = true;
1564 }
1565 }
1566
1567 /*
1568 * The following private methods are mainly used to improve the
1569 * readability of the code. In order to let the Java compiler easily
1570 * inline them, we should not put many assertions or error checks in them.
1571 */
1572
1573 /**
1574 * Indicates whether a particular flag is set or not.
1575 */
1576 private boolean has(int f) {
1577 return (flags & f) != 0;
1578 }
1579
1580 /**
1581 * Match next character, signal error if failed.
1582 */
1583 private void accept(int ch, String s) {
1584 int testChar = temp[cursor++];
1585 if (has(COMMENTS))
1586 testChar = parsePastWhitespace(testChar);
1587 if (ch != testChar) {
1588 throw error(s);
1589 }
1590 }
1591
1592 /**
1593 * Mark the end of pattern with a specific character.
1594 */
1595 private void mark(int c) {
1596 temp[patternLength] = c;
1597 }
1598
1599 /**
1600 * Peek the next character, and do not advance the cursor.
1601 */
1602 private int peek() {
1603 int ch = temp[cursor];
1604 if (has(COMMENTS))
1605 ch = peekPastWhitespace(ch);
1606 return ch;
1607 }
1608
1609 /**
1610 * Read the next character, and advance the cursor by one.
1611 */
1612 private int read() {
1613 int ch = temp[cursor++];
1614 if (has(COMMENTS))
1615 ch = parsePastWhitespace(ch);
1616 return ch;
1617 }
1618
1619 /**
1620 * Read the next character, and advance the cursor by one,
1621 * ignoring the COMMENTS setting
1622 */
1623 private int readEscaped() {
1624 int ch = temp[cursor++];
1625 return ch;
1626 }
1627
1628 /**
1629 * Advance the cursor by one, and peek the next character.
1630 */
1631 private int next() {
1632 int ch = temp[++cursor];
1633 if (has(COMMENTS))
1634 ch = peekPastWhitespace(ch);
1635 return ch;
1636 }
1637
1638 /**
1639 * Advance the cursor by one, and peek the next character,
1640 * ignoring the COMMENTS setting
1641 */
1642 private int nextEscaped() {
1643 int ch = temp[++cursor];
1644 return ch;
1645 }
1646
1647 /**
1648 * If in xmode peek past whitespace and comments.
1649 */
1650 private int peekPastWhitespace(int ch) {
1651 while (ASCII.isSpace(ch) || ch == '#') {
1652 while (ASCII.isSpace(ch))
1653 ch = temp[++cursor];
1654 if (ch == '#') {
1655 ch = peekPastLine();
1656 }
1657 }
1658 return ch;
1659 }
1660
1661 /**
1662 * If in xmode parse past whitespace and comments.
1663 */
1664 private int parsePastWhitespace(int ch) {
1665 while (ASCII.isSpace(ch) || ch == '#') {
1666 while (ASCII.isSpace(ch))
1667 ch = temp[cursor++];
1668 if (ch == '#')
1669 ch = parsePastLine();
1670 }
1671 return ch;
1672 }
1673
1674 /**
1675 * xmode parse past comment to end of line.
1676 */
1677 private int parsePastLine() {
1678 int ch = temp[cursor++];
1679 while (ch != 0 && !isLineSeparator(ch))
1680 ch = temp[cursor++];
1681 return ch;
1682 }
1683
1684 /**
1685 * xmode peek past comment to end of line.
1686 */
1687 private int peekPastLine() {
1688 int ch = temp[++cursor];
1689 while (ch != 0 && !isLineSeparator(ch))
1690 ch = temp[++cursor];
1691 return ch;
1692 }
1693
1694 /**
1695 * Determines if character is a line separator in the current mode
1696 */
1697 private boolean isLineSeparator(int ch) {
1698 if (has(UNIX_LINES)) {
1699 return ch == '\n';
1700 } else {
1701 return (ch == '\n' ||
1702 ch == '\r' ||
1703 (ch|1) == '\u2029' ||
1704 ch == '\u0085');
1705 }
1706 }
1707
1708 /**
1709 * Read the character after the next one, and advance the cursor by two.
1710 */
1711 private int skip() {
1712 int i = cursor;
1713 int ch = temp[i+1];
1714 cursor = i + 2;
1715 return ch;
1716 }
1717
1718 /**
1719 * Unread one next character, and retreat cursor by one.
1720 */
1721 private void unread() {
1722 cursor--;
1723 }
1724
1725 /**
1726 * Internal method used for handling all syntax errors. The pattern is
1727 * displayed with a pointer to aid in locating the syntax error.
1728 */
1729 private PatternSyntaxException error(String s) {
1730 return new PatternSyntaxException(s, normalizedPattern, cursor - 1);
1731 }
1732
1733 /**
1734 * Determines if there is any supplementary character or unpaired
1735 * surrogate in the specified range.
1736 */
1737 private boolean findSupplementary(int start, int end) {
1738 for (int i = start; i < end; i++) {
1739 if (isSupplementary(temp[i]))
1740 return true;
1741 }
1742 return false;
1743 }
1744
1745 /**
1746 * Determines if the specified code point is a supplementary
1747 * character or unpaired surrogate.
1748 */
1749 private static final boolean isSupplementary(int ch) {
1750 return ch >= Character.MIN_SUPPLEMENTARY_CODE_POINT || isSurrogate(ch);
1751 }
1752
1753 /**
1754 * The following methods handle the main parsing. They are sorted
1755 * according to their precedence order, the lowest one first.
1756 */
1757
1758 /**
1759 * The expression is parsed with branch nodes added for alternations.
1760 * This may be called recursively to parse sub expressions that may
1761 * contain alternations.
1762 */
1763 private Node expr(Node end) {
1764 Node prev = null;
1765 Node firstTail = null;
1766 Node branchConn = null;
1767
1768 for (;;) {
1769 Node node = sequence(end);
1770 Node nodeTail = root; //double return
1771 if (prev == null) {
1772 prev = node;
1773 firstTail = nodeTail;
1774 } else {
1775 // Branch
1776 if (branchConn == null) {
1777 branchConn = new BranchConn();
1778 branchConn.next = end;
1779 }
1780 if (node == end) {
1781 // if the node returned from sequence() is "end"
1782 // we have an empty expr, set a null atom into
1783 // the branch to indicate to go "next" directly.
1784 node = null;
1785 } else {
1786 // the "tail.next" of each atom goes to branchConn
1787 nodeTail.next = branchConn;
1788 }
1789 if (prev instanceof Branch) {
1790 ((Branch)prev).add(node);
1791 } else {
1792 if (prev == end) {
1793 prev = null;
1794 } else {
1795 // replace the "end" with "branchConn" at its tail.next
1796 // when put the "prev" into the branch as the first atom.
1797 firstTail.next = branchConn;
1798 }
1799 prev = new Branch(prev, node, branchConn);
1800 }
1801 }
1802 if (peek() != '|') {
1803 return prev;
1804 }
1805 next();
1806 }
1807 }
1808
1809 /**
1810 * Parsing of sequences between alternations.
1811 */
1812 private Node sequence(Node end) {
1813 Node head = null;
1814 Node tail = null;
1815 Node node = null;
1816 LOOP:
1817 for (;;) {
1818 int ch = peek();
1819 switch (ch) {
1820 case '(':
1821 // Because group handles its own closure,
1822 // we need to treat it differently
1823 node = group0();
1824 // Check for comment or flag group
1825 if (node == null)
1826 continue;
1827 if (head == null)
1828 head = node;
1829 else
1830 tail.next = node;
1831 // Double return: Tail was returned in root
1832 tail = root;
1833 continue;
1834 case '[':
1835 node = clazz(true);
1836 break;
1837 case '\\':
1838 ch = nextEscaped();
1839 if (ch == 'p' || ch == 'P') {
1840 boolean oneLetter = true;
1841 boolean comp = (ch == 'P');
1842 ch = next(); // Consume { if present
1843 if (ch != '{') {
1844 unread();
1845 } else {
1846 oneLetter = false;
1847 }
1848 node = family(oneLetter).maybeComplement(comp);
1849 } else {
1850 unread();
1851 node = atom();
1852 }
1853 break;
1854 case '^':
1855 next();
1856 if (has(MULTILINE)) {
1857 if (has(UNIX_LINES))
1858 node = new UnixCaret();
1859 else
1860 node = new Caret();
1861 } else {
1862 node = new Begin();
1863 }
1864 break;
1865 case '$':
1866 next();
1867 if (has(UNIX_LINES))
1868 node = new UnixDollar(has(MULTILINE));
1869 else
1870 node = new Dollar(has(MULTILINE));
1871 break;
1872 case '.':
1873 next();
1874 if (has(DOTALL)) {
1875 node = new All();
1876 } else {
1877 if (has(UNIX_LINES))
1878 node = new UnixDot();
1879 else {
1880 node = new Dot();
1881 }
1882 }
1883 break;
1884 case '|':
1885 case ')':
1886 break LOOP;
1887 case ']': // Now interpreting dangling ] and } as literals
1888 case '}':
1889 node = atom();
1890 break;
1891 case '?':
1892 case '*':
1893 case '+':
1894 next();
1895 throw error("Dangling meta character '" + ((char)ch) + "'");
1896 case 0:
1897 if (cursor >= patternLength) {
1898 break LOOP;
1899 }
1900 // Fall through
1901 default:
1902 node = atom();
1903 break;
1904 }
1905
1906 node = closure(node);
1907
1908 if (head == null) {
1909 head = tail = node;
1910 } else {
1911 tail.next = node;
1912 tail = node;
1913 }
1914 }
1915 if (head == null) {
1916 return end;
1917 }
1918 tail.next = end;
1919 root = tail; //double return
1920 return head;
1921 }
1922
1923 /**
1924 * Parse and add a new Single or Slice.
1925 */
1926 private Node atom() {
1927 int first = 0;
1928 int prev = -1;
1929 boolean hasSupplementary = false;
1930 int ch = peek();
1931 for (;;) {
1932 switch (ch) {
1933 case '*':
1934 case '+':
1935 case '?':
1936 case '{':
1937 if (first > 1) {
1938 cursor = prev; // Unwind one character
1939 first--;
1940 }
1941 break;
1942 case '$':
1943 case '.':
1944 case '^':
1945 case '(':
1946 case '[':
1947 case '|':
1948 case ')':
1949 break;
1950 case '\\':
1951 ch = nextEscaped();
1952 if (ch == 'p' || ch == 'P') { // Property
1953 if (first > 0) { // Slice is waiting; handle it first
1954 unread();
1955 break;
1956 } else { // No slice; just return the family node
1957 boolean comp = (ch == 'P');
1958 boolean oneLetter = true;
1959 ch = next(); // Consume { if present
1960 if (ch != '{')
1961 unread();
1962 else
1963 oneLetter = false;
1964 return family(oneLetter).maybeComplement(comp);
1965 }
1966 }
1967 unread();
1968 prev = cursor;
1969 ch = escape(false, first == 0);
1970 if (ch >= 0) {
1971 append(ch, first);
1972 first++;
1973 if (isSupplementary(ch)) {
1974 hasSupplementary = true;
1975 }
1976 ch = peek();
1977 continue;
1978 } else if (first == 0) {
1979 return root;
1980 }
1981 // Unwind meta escape sequence
1982 cursor = prev;
1983 break;
1984 case 0:
1985 if (cursor >= patternLength) {
1986 break;
1987 }
1988 // Fall through
1989 default:
1990 prev = cursor;
1991 append(ch, first);
1992 first++;
1993 if (isSupplementary(ch)) {
1994 hasSupplementary = true;
1995 }
1996 ch = next();
1997 continue;
1998 }
1999 break;
2000 }
2001 if (first == 1) {
2002 return newSingle(buffer[0]);
2003 } else {
2004 return newSlice(buffer, first, hasSupplementary);
2005 }
2006 }
2007
2008 private void append(int ch, int len) {
2009 if (len >= buffer.length) {
2010 int[] tmp = new int[len+len];
2011 System.arraycopy(buffer, 0, tmp, 0, len);
2012 buffer = tmp;
2013 }
2014 buffer[len] = ch;
2015 }
2016
2017 /**
2018 * Parses a backref greedily, taking as many numbers as it
2019 * can. The first digit is always treated as a backref, but
2020 * multi digit numbers are only treated as a backref if at
2021 * least that many backrefs exist at this point in the regex.
2022 */
2023 private Node ref(int refNum) {
2024 boolean done = false;
2025 while(!done) {
2026 int ch = peek();
2027 switch(ch) {
2028 case '0':
2029 case '1':
2030 case '2':
2031 case '3':
2032 case '4':
2033 case '5':
2034 case '6':
2035 case '7':
2036 case '8':
2037 case '9':
2038 int newRefNum = (refNum * 10) + (ch - '0');
2039 // Add another number if it doesn't make a group
2040 // that doesn't exist
2041 if (capturingGroupCount - 1 < newRefNum) {
2042 done = true;
2043 break;
2044 }
2045 refNum = newRefNum;
2046 read();
2047 break;
2048 default:
2049 done = true;
2050 break;
2051 }
2052 }
2053 if (has(CASE_INSENSITIVE))
2054 return new CIBackRef(refNum, has(UNICODE_CASE));
2055 else
2056 return new BackRef(refNum);
2057 }
2058
2059 /**
2060 * Parses an escape sequence to determine the actual value that needs
2061 * to be matched.
2062 * If -1 is returned and create was true a new object was added to the tree
2063 * to handle the escape sequence.
2064 * If the returned value is greater than zero, it is the value that
2065 * matches the escape sequence.
2066 */
2067 private int escape(boolean inclass, boolean create) {
2068 int ch = skip();
2069 switch (ch) {
2070 case '0':
2071 return o();
2072 case '1':
2073 case '2':
2074 case '3':
2075 case '4':
2076 case '5':
2077 case '6':
2078 case '7':
2079 case '8':
2080 case '9':
2081 if (inclass) break;
2082 if (create) {
2083 root = ref((ch - '0'));
2084 }
2085 return -1;
2086 case 'A':
2087 if (inclass) break;
2088 if (create) root = new Begin();
2089 return -1;
2090 case 'B':
2091 if (inclass) break;
2092 if (create) root = new Bound(Bound.NONE);
2093 return -1;
2094 case 'C':
2095 break;
2096 case 'D':
2097 if (create) root = new Ctype(ASCII.DIGIT).complement();
2098 return -1;
2099 case 'E':
2100 case 'F':
2101 break;
2102 case 'G':
2103 if (inclass) break;
2104 if (create) root = new LastMatch();
2105 return -1;
2106 case 'H':
2107 case 'I':
2108 case 'J':
2109 case 'K':
2110 case 'L':
2111 case 'M':
2112 case 'N':
2113 case 'O':
2114 case 'P':
2115 case 'Q':
2116 case 'R':
2117 break;
2118 case 'S':
2119 if (create) root = new Ctype(ASCII.SPACE).complement();
2120 return -1;
2121 case 'T':
2122 case 'U':
2123 case 'V':
2124 break;
2125 case 'W':
2126 if (create) root = new Ctype(ASCII.WORD).complement();
2127 return -1;
2128 case 'X':
2129 case 'Y':
2130 break;
2131 case 'Z':
2132 if (inclass) break;
2133 if (create) {
2134 if (has(UNIX_LINES))
2135 root = new UnixDollar(false);
2136 else
2137 root = new Dollar(false);
2138 }
2139 return -1;
2140 case 'a':
2141 return '\007';
2142 case 'b':
2143 if (inclass) break;
2144 if (create) root = new Bound(Bound.BOTH);
2145 return -1;
2146 case 'c':
2147 return c();
2148 case 'd':
2149 if (create) root = new Ctype(ASCII.DIGIT);
2150 return -1;
2151 case 'e':
2152 return '\033';
2153 case 'f':
2154 return '\f';
2155 case 'g':
2156 case 'h':
2157 case 'i':
2158 case 'j':
2159 case 'k':
2160 case 'l':
2161 case 'm':
2162 break;
2163 case 'n':
2164 return '\n';
2165