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