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