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