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