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