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