Pattern.java revision 17465:cfdcaedd6da2
191671Sume/* 262587Sitojun * Copyright (c) 1999, 2017, Oracle and/or its affiliates. All rights reserved. 355009Sshin * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4116174Sobrien * 555009Sshin * This code is free software; you can redistribute it and/or modify it 655009Sshin * under the terms of the GNU General Public License version 2 only, as 755009Sshin * published by the Free Software Foundation. Oracle designates this 855009Sshin * particular file as subject to the "Classpath" exception as provided 955009Sshin * by Oracle in the LICENSE file that accompanied this code. 1055009Sshin * 1155009Sshin * This code is distributed in the hope that it will be useful, but WITHOUT 1255009Sshin * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 1355009Sshin * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 1455009Sshin * version 2 for more details (a copy is included in the LICENSE file that 1555009Sshin * accompanied this code). 1655009Sshin * 1755009Sshin * You should have received a copy of the GNU General Public License version 1855009Sshin * 2 along with this work; if not, write to the Free Software Foundation, 1955009Sshin * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 2055009Sshin * 2155009Sshin * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 2255009Sshin * or visit www.oracle.com if you need additional information or have any 2355009Sshin * questions. 2455009Sshin */ 2555009Sshin 2655009Sshinpackage java.util.regex; 2755009Sshin 2855009Sshinimport java.text.Normalizer; 2955009Sshinimport java.text.Normalizer.Form; 3055009Sshinimport java.util.Locale; 3155009Sshinimport java.util.Iterator; 3255009Sshinimport java.util.Map; 3355009Sshinimport java.util.ArrayList; 3455009Sshinimport java.util.HashMap; 3555009Sshinimport java.util.LinkedHashSet; 3655009Sshinimport java.util.List; 3755009Sshinimport java.util.Set; 3855009Sshinimport java.util.Arrays; 3955009Sshinimport java.util.NoSuchElementException; 4055009Sshinimport java.util.Spliterator; 4155009Sshinimport java.util.Spliterators; 4255009Sshinimport java.util.function.Predicate; 4355009Sshinimport java.util.stream.Stream; 4455009Sshinimport java.util.stream.StreamSupport; 4555009Sshin 4655009Sshin 4755009Sshin/** 4855009Sshin * A compiled representation of a regular expression. 4955009Sshin * 5055009Sshin * <p> A regular expression, specified as a string, must first be compiled into 5155009Sshin * an instance of this class. The resulting pattern can then be used to create 5255009Sshin * a {@link Matcher} object that can match arbitrary {@linkplain 5355009Sshin * java.lang.CharSequence character sequences} against the regular 5455009Sshin * expression. All of the state involved in performing a match resides in the 5555009Sshin * matcher, so many matchers can share the same pattern. 5655009Sshin * 5755009Sshin * <p> A typical invocation sequence is thus 5855009Sshin * 5955009Sshin * <blockquote><pre> 6055009Sshin * Pattern p = Pattern.{@link #compile compile}("a*b"); 6155009Sshin * Matcher m = p.{@link #matcher matcher}("aaaaab"); 62116174Sobrien * boolean b = m.{@link Matcher#matches matches}();</pre></blockquote> 63116174Sobrien * 64116174Sobrien * <p> A {@link #matches matches} method is defined by this class as a 6555009Sshin * convenience for when a regular expression is used just once. This method 6655009Sshin * compiles an expression and matches an input sequence against it in a single 6755009Sshin * invocation. The statement 6855009Sshin * 6955009Sshin * <blockquote><pre> 7055009Sshin * boolean b = Pattern.matches("a*b", "aaaaab");</pre></blockquote> 7155009Sshin * 7278064Sume * is equivalent to the three statements above, though for repeated matches it 7378064Sume * is less efficient since it does not allow the compiled pattern to be reused. 7478064Sume * 7578064Sume * <p> Instances of this class are immutable and are safe for use by multiple 7678064Sume * concurrent threads. Instances of the {@link Matcher} class are not safe for 7778064Sume * such use. 7855009Sshin * 7978064Sume * 8078064Sume * <h3><a id="sum">Summary of regular-expression constructs</a></h3> 8155009Sshin * 8291671Sume * <table class="borderless"> 8378064Sume * <caption style="display:none">Regular expression constructs, and what they match</caption> 8455009Sshin * <thead> 8578064Sume * <tr style="text-align:left"> 8678064Sume * <th style="text-align:left" id="construct">Construct</th> 8755009Sshin * <th style="text-align:left" id="matches">Matches</th> 8878064Sume * </tr> 8955009Sshin * </thead> 9078064Sume * <tbody> 9178064Sume * 9278064Sume * <tr><th> </th></tr> 9355009Sshin * <tr style="text-align:left"><th colspan="2" id="characters">Characters</th></tr> 9478064Sume * 9578064Sume * <tr><td style="vertical-align:top" headers="construct characters"><i>x</i></td> 9678064Sume * <td headers="matches">The character <i>x</i></td></tr> 9755009Sshin * <tr><td style="vertical-align:top" headers="construct characters">{@code \\}</td> 9878064Sume * <td headers="matches">The backslash character</td></tr> 9978064Sume * <tr><td style="vertical-align:top" headers="construct characters">{@code \0}<i>n</i></td> 10078064Sume * <td headers="matches">The character with octal value {@code 0}<i>n</i> 10155009Sshin * (0 {@code <=} <i>n</i> {@code <=} 7)</td></tr> 10278064Sume * <tr><td style="vertical-align:top" headers="construct characters">{@code \0}<i>nn</i></td> 10378064Sume * <td headers="matches">The character with octal value {@code 0}<i>nn</i> 10478064Sume * (0 {@code <=} <i>n</i> {@code <=} 7)</td></tr> 10555009Sshin * <tr><td style="vertical-align:top" headers="construct characters">{@code \0}<i>mnn</i></td> 10678064Sume * <td headers="matches">The character with octal value {@code 0}<i>mnn</i> 10778064Sume * (0 {@code <=} <i>m</i> {@code <=} 3, 10855009Sshin * 0 {@code <=} <i>n</i> {@code <=} 7)</td></tr> 10978064Sume * <tr><td style="vertical-align:top" headers="construct characters">{@code \x}<i>hh</i></td> 11078064Sume * <td headers="matches">The character with hexadecimal value {@code 0x}<i>hh</i></td></tr> 11178064Sume * <tr><td style="vertical-align:top" headers="construct characters"><code>\u</code><i>hhhh</i></td> 11291671Sume * <td headers="matches">The character with hexadecimal value {@code 0x}<i>hhhh</i></td></tr> 11378064Sume * <tr><td style="vertical-align:top" headers="construct characters"><code>\x</code><i>{h...h}</i></td> 11478064Sume * <td headers="matches">The character with hexadecimal value {@code 0x}<i>h...h</i> 11578064Sume * ({@link java.lang.Character#MIN_CODE_POINT Character.MIN_CODE_POINT} 11655009Sshin * <= {@code 0x}<i>h...h</i> <= 11778064Sume * {@link java.lang.Character#MAX_CODE_POINT Character.MAX_CODE_POINT})</td></tr> 11878064Sume * <tr><td style="vertical-align:top" headers="construct characters"><code>\N{</code><i>name</i><code>}</code></td> 11991671Sume * <td headers="matches">The character with Unicode character name <i>'name'</i></td></tr> 12078064Sume * <tr><td style="vertical-align:top" headers="matches">{@code \t}</td> 12178064Sume * <td headers="matches">The tab character (<code>'\u0009'</code>)</td></tr> 12255009Sshin * <tr><td style="vertical-align:top" headers="construct characters">{@code \n}</td> 12378064Sume * <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 793public 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. 1614loop: 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) { 3891 if (seq.charAt(i) == 0x0A && 3892 next.match(matcher, i + 1, seq)) { 3893 return true; 3894 } 3895 } else { 3896 matcher.hitEnd = true; 3897 } 3898 return next.match(matcher, i, seq); 3899 } 3900 } else { 3901 matcher.hitEnd = true; 3902 } 3903 return false; 3904 } 3905 boolean study(TreeInfo info) { 3906 info.minLength++; 3907 info.maxLength += 2; 3908 return next.study(info); 3909 } 3910 } 3911 3912 /** 3913 * Abstract node class to match one character satisfying some 3914 * boolean property. 3915 */ 3916 static class CharProperty extends Node { 3917 CharPredicate predicate; 3918 3919 CharProperty (CharPredicate predicate) { 3920 this.predicate = predicate; 3921 } 3922 boolean match(Matcher matcher, int i, CharSequence seq) { 3923 if (i < matcher.to) { 3924 int ch = Character.codePointAt(seq, i); 3925 return predicate.is(ch) && 3926 next.match(matcher, i + Character.charCount(ch), seq); 3927 } else { 3928 matcher.hitEnd = true; 3929 return false; 3930 } 3931 } 3932 boolean study(TreeInfo info) { 3933 info.minLength++; 3934 info.maxLength++; 3935 return next.study(info); 3936 } 3937 } 3938 3939 /** 3940 * Optimized version of CharProperty that works only for 3941 * properties never satisfied by Supplementary characters. 3942 */ 3943 private static class BmpCharProperty extends CharProperty { 3944 BmpCharProperty (BmpCharPredicate predicate) { 3945 super(predicate); 3946 } 3947 boolean match(Matcher matcher, int i, CharSequence seq) { 3948 if (i < matcher.to) { 3949 return predicate.is(seq.charAt(i)) && 3950 next.match(matcher, i + 1, seq); 3951 } else { 3952 matcher.hitEnd = true; 3953 return false; 3954 } 3955 } 3956 } 3957 3958 private static class NFCCharProperty extends Node { 3959 CharPredicate predicate; 3960 NFCCharProperty (CharPredicate predicate) { 3961 this.predicate = predicate; 3962 } 3963 3964 boolean match(Matcher matcher, int i, CharSequence seq) { 3965 if (i < matcher.to) { 3966 int ch0 = Character.codePointAt(seq, i); 3967 int n = Character.charCount(ch0); 3968 int j = i + n; 3969 while (j < matcher.to) { 3970 int ch1 = Character.codePointAt(seq, j); 3971 if (Grapheme.isBoundary(ch0, ch1)) 3972 break; 3973 ch0 = ch1; 3974 j += Character.charCount(ch1); 3975 } 3976 if (i + n == j) { // single, assume nfc cp 3977 if (predicate.is(ch0)) 3978 return next.match(matcher, j, seq); 3979 } else { 3980 while (i + n < j) { 3981 String nfc = Normalizer.normalize( 3982 seq.toString().substring(i, j), Normalizer.Form.NFC); 3983 if (nfc.codePointCount(0, nfc.length()) == 1) { 3984 if (predicate.is(nfc.codePointAt(0)) && 3985 next.match(matcher, j, seq)) { 3986 return true; 3987 } 3988 } 3989 3990 ch0 = Character.codePointBefore(seq, j); 3991 j -= Character.charCount(ch0); 3992 } 3993 } 3994 if (j < matcher.to) 3995 return false; 3996 } 3997 matcher.hitEnd = true; 3998 return false; 3999 } 4000 4001 boolean study(TreeInfo info) { 4002 info.minLength++; 4003 info.deterministic = false; 4004 return next.study(info); 4005 } 4006 } 4007 4008 /** 4009 * Node class that matches an unicode extended grapheme cluster 4010 */ 4011 static class XGrapheme extends Node { 4012 boolean match(Matcher matcher, int i, CharSequence seq) { 4013 if (i < matcher.to) { 4014 int ch0 = Character.codePointAt(seq, i); 4015 i += Character.charCount(ch0); 4016 while (i < matcher.to) { 4017 int ch1 = Character.codePointAt(seq, i); 4018 if (Grapheme.isBoundary(ch0, ch1)) 4019 break; 4020 ch0 = ch1; 4021 i += Character.charCount(ch1); 4022 } 4023 return next.match(matcher, i, seq); 4024 } 4025 matcher.hitEnd = true; 4026 return false; 4027 } 4028 4029 boolean study(TreeInfo info) { 4030 info.minLength++; 4031 info.deterministic = false; 4032 return next.study(info); 4033 } 4034 } 4035 4036 /** 4037 * Node class that handles grapheme boundaries 4038 */ 4039 static class GraphemeBound extends Node { 4040 boolean match(Matcher matcher, int i, CharSequence seq) { 4041 int startIndex = matcher.from; 4042 int endIndex = matcher.to; 4043 if (matcher.transparentBounds) { 4044 startIndex = 0; 4045 endIndex = matcher.getTextLength(); 4046 } 4047 if (i == startIndex) { 4048 return next.match(matcher, i, seq); 4049 } 4050 if (i < endIndex) { 4051 if (Character.isSurrogatePair(seq.charAt(i-1), seq.charAt(i)) || 4052 !Grapheme.isBoundary(Character.codePointBefore(seq, i), 4053 Character.codePointAt(seq, i))) { 4054 return false; 4055 } 4056 } else { 4057 matcher.hitEnd = true; 4058 matcher.requireEnd = true; 4059 } 4060 return next.match(matcher, i, seq); 4061 } 4062 } 4063 4064 /** 4065 * Base class for all Slice nodes 4066 */ 4067 static class SliceNode extends Node { 4068 int[] buffer; 4069 SliceNode(int[] buf) { 4070 buffer = buf; 4071 } 4072 boolean study(TreeInfo info) { 4073 info.minLength += buffer.length; 4074 info.maxLength += buffer.length; 4075 return next.study(info); 4076 } 4077 } 4078 4079 /** 4080 * Node class for a case sensitive/BMP-only sequence of literal 4081 * characters. 4082 */ 4083 static class Slice extends SliceNode { 4084 Slice(int[] buf) { 4085 super(buf); 4086 } 4087 boolean match(Matcher matcher, int i, CharSequence seq) { 4088 int[] buf = buffer; 4089 int len = buf.length; 4090 for (int j=0; j<len; j++) { 4091 if ((i+j) >= matcher.to) { 4092 matcher.hitEnd = true; 4093 return false; 4094 } 4095 if (buf[j] != seq.charAt(i+j)) 4096 return false; 4097 } 4098 return next.match(matcher, i+len, seq); 4099 } 4100 } 4101 4102 /** 4103 * Node class for a case_insensitive/BMP-only sequence of literal 4104 * characters. 4105 */ 4106 static class SliceI extends SliceNode { 4107 SliceI(int[] buf) { 4108 super(buf); 4109 } 4110 boolean match(Matcher matcher, int i, CharSequence seq) { 4111 int[] buf = buffer; 4112 int len = buf.length; 4113 for (int j=0; j<len; j++) { 4114 if ((i+j) >= matcher.to) { 4115 matcher.hitEnd = true; 4116 return false; 4117 } 4118 int c = seq.charAt(i+j); 4119 if (buf[j] != c && 4120 buf[j] != ASCII.toLower(c)) 4121 return false; 4122 } 4123 return next.match(matcher, i+len, seq); 4124 } 4125 } 4126 4127 /** 4128 * Node class for a unicode_case_insensitive/BMP-only sequence of 4129 * literal characters. Uses unicode case folding. 4130 */ 4131 static final class SliceU extends SliceNode { 4132 SliceU(int[] buf) { 4133 super(buf); 4134 } 4135 boolean match(Matcher matcher, int i, CharSequence seq) { 4136 int[] buf = buffer; 4137 int len = buf.length; 4138 for (int j=0; j<len; j++) { 4139 if ((i+j) >= matcher.to) { 4140 matcher.hitEnd = true; 4141 return false; 4142 } 4143 int c = seq.charAt(i+j); 4144 if (buf[j] != c && 4145 buf[j] != Character.toLowerCase(Character.toUpperCase(c))) 4146 return false; 4147 } 4148 return next.match(matcher, i+len, seq); 4149 } 4150 } 4151 4152 /** 4153 * Node class for a case sensitive sequence of literal characters 4154 * including supplementary characters. 4155 */ 4156 static final class SliceS extends Slice { 4157 SliceS(int[] buf) { 4158 super(buf); 4159 } 4160 boolean match(Matcher matcher, int i, CharSequence seq) { 4161 int[] buf = buffer; 4162 int x = i; 4163 for (int j = 0; j < buf.length; j++) { 4164 if (x >= matcher.to) { 4165 matcher.hitEnd = true; 4166 return false; 4167 } 4168 int c = Character.codePointAt(seq, x); 4169 if (buf[j] != c) 4170 return false; 4171 x += Character.charCount(c); 4172 if (x > matcher.to) { 4173 matcher.hitEnd = true; 4174 return false; 4175 } 4176 } 4177 return next.match(matcher, x, seq); 4178 } 4179 } 4180 4181 /** 4182 * Node class for a case insensitive sequence of literal characters 4183 * including supplementary characters. 4184 */ 4185 static class SliceIS extends SliceNode { 4186 SliceIS(int[] buf) { 4187 super(buf); 4188 } 4189 int toLower(int c) { 4190 return ASCII.toLower(c); 4191 } 4192 boolean match(Matcher matcher, int i, CharSequence seq) { 4193 int[] buf = buffer; 4194 int x = i; 4195 for (int j = 0; j < buf.length; j++) { 4196 if (x >= matcher.to) { 4197 matcher.hitEnd = true; 4198 return false; 4199 } 4200 int c = Character.codePointAt(seq, x); 4201 if (buf[j] != c && buf[j] != toLower(c)) 4202 return false; 4203 x += Character.charCount(c); 4204 if (x > matcher.to) { 4205 matcher.hitEnd = true; 4206 return false; 4207 } 4208 } 4209 return next.match(matcher, x, seq); 4210 } 4211 } 4212 4213 /** 4214 * Node class for a case insensitive sequence of literal characters. 4215 * Uses unicode case folding. 4216 */ 4217 static final class SliceUS extends SliceIS { 4218 SliceUS(int[] buf) { 4219 super(buf); 4220 } 4221 int toLower(int c) { 4222 return Character.toLowerCase(Character.toUpperCase(c)); 4223 } 4224 } 4225 4226 /** 4227 * The 0 or 1 quantifier. This one class implements all three types. 4228 */ 4229 static final class Ques extends Node { 4230 Node atom; 4231 Qtype type; 4232 Ques(Node node, Qtype type) { 4233 this.atom = node; 4234 this.type = type; 4235 } 4236 boolean match(Matcher matcher, int i, CharSequence seq) { 4237 switch (type) { 4238 case GREEDY: 4239 return (atom.match(matcher, i, seq) && next.match(matcher, matcher.last, seq)) 4240 || next.match(matcher, i, seq); 4241 case LAZY: 4242 return next.match(matcher, i, seq) 4243 || (atom.match(matcher, i, seq) && next.match(matcher, matcher.last, seq)); 4244 case POSSESSIVE: 4245 if (atom.match(matcher, i, seq)) i = matcher.last; 4246 return next.match(matcher, i, seq); 4247 default: 4248 return atom.match(matcher, i, seq) && next.match(matcher, matcher.last, seq); 4249 } 4250 } 4251 boolean study(TreeInfo info) { 4252 if (type != Qtype.INDEPENDENT) { 4253 int minL = info.minLength; 4254 atom.study(info); 4255 info.minLength = minL; 4256 info.deterministic = false; 4257 return next.study(info); 4258 } else { 4259 atom.study(info); 4260 return next.study(info); 4261 } 4262 } 4263 } 4264 4265 /** 4266 * Handles the greedy style repetition with the minimum either be 4267 * 0 or 1 and the maximum be MAX_REPS, for * and + quantifier. 4268 */ 4269 static class CharPropertyGreedy extends Node { 4270 final CharPredicate predicate; 4271 final int cmin; 4272 4273 CharPropertyGreedy(CharProperty cp, int cmin) { 4274 this.predicate = cp.predicate; 4275 this.cmin = cmin; 4276 } 4277 boolean match(Matcher matcher, int i, CharSequence seq) { 4278 int n = 0; 4279 int to = matcher.to; 4280 // greedy, all the way down 4281 while (i < to) { 4282 int ch = Character.codePointAt(seq, i); 4283 if (!predicate.is(ch)) 4284 break; 4285 i += Character.charCount(ch); 4286 n++; 4287 } 4288 if (i >= to) { 4289 matcher.hitEnd = true; 4290 } 4291 while (n >= cmin) { 4292 if (next.match(matcher, i, seq)) 4293 return true; 4294 if (n == cmin) 4295 return false; 4296 // backing off if match fails 4297 int ch = Character.codePointBefore(seq, i); 4298 i -= Character.charCount(ch); 4299 n--; 4300 } 4301 return false; 4302 } 4303 4304 boolean study(TreeInfo info) { 4305 info.minLength += cmin; 4306 if (info.maxValid) { 4307 info.maxLength += MAX_REPS; 4308 } 4309 info.deterministic = false; 4310 return next.study(info); 4311 } 4312 } 4313 4314 static final class BmpCharPropertyGreedy extends CharPropertyGreedy { 4315 4316 BmpCharPropertyGreedy(BmpCharProperty bcp, int cmin) { 4317 super(bcp, cmin); 4318 } 4319 4320 boolean match(Matcher matcher, int i, CharSequence seq) { 4321 int n = 0; 4322 int to = matcher.to; 4323 while (i < to && predicate.is(seq.charAt(i))) { 4324 i++; n++; 4325 } 4326 if (i >= to) { 4327 matcher.hitEnd = true; 4328 } 4329 while (n >= cmin) { 4330 if (next.match(matcher, i, seq)) 4331 return true; 4332 i--; n--; // backing off if match fails 4333 } 4334 return false; 4335 } 4336 } 4337 4338 /** 4339 * Handles the curly-brace style repetition with a specified minimum and 4340 * maximum occurrences. The * quantifier is handled as a special case. 4341 * This class handles the three types. 4342 */ 4343 static final class Curly extends Node { 4344 Node atom; 4345 Qtype type; 4346 int cmin; 4347 int cmax; 4348 4349 Curly(Node node, int cmin, int cmax, Qtype type) { 4350 this.atom = node; 4351 this.type = type; 4352 this.cmin = cmin; 4353 this.cmax = cmax; 4354 } 4355 boolean match(Matcher matcher, int i, CharSequence seq) { 4356 int j; 4357 for (j = 0; j < cmin; j++) { 4358 if (atom.match(matcher, i, seq)) { 4359 i = matcher.last; 4360 continue; 4361 } 4362 return false; 4363 } 4364 if (type == Qtype.GREEDY) 4365 return match0(matcher, i, j, seq); 4366 else if (type == Qtype.LAZY) 4367 return match1(matcher, i, j, seq); 4368 else 4369 return match2(matcher, i, j, seq); 4370 } 4371 // Greedy match. 4372 // i is the index to start matching at 4373 // j is the number of atoms that have matched 4374 boolean match0(Matcher matcher, int i, int j, CharSequence seq) { 4375 if (j >= cmax) { 4376 // We have matched the maximum... continue with the rest of 4377 // the regular expression 4378 return next.match(matcher, i, seq); 4379 } 4380 int backLimit = j; 4381 while (atom.match(matcher, i, seq)) { 4382 // k is the length of this match 4383 int k = matcher.last - i; 4384 if (k == 0) // Zero length match 4385 break; 4386 // Move up index and number matched 4387 i = matcher.last; 4388 j++; 4389 // We are greedy so match as many as we can 4390 while (j < cmax) { 4391 if (!atom.match(matcher, i, seq)) 4392 break; 4393 if (i + k != matcher.last) { 4394 if (match0(matcher, matcher.last, j+1, seq)) 4395 return true; 4396 break; 4397 } 4398 i += k; 4399 j++; 4400 } 4401 // Handle backing off if match fails 4402 while (j >= backLimit) { 4403 if (next.match(matcher, i, seq)) 4404 return true; 4405 i -= k; 4406 j--; 4407 } 4408 return false; 4409 } 4410 return next.match(matcher, i, seq); 4411 } 4412 // Reluctant match. At this point, the minimum has been satisfied. 4413 // i is the index to start matching at 4414 // j is the number of atoms that have matched 4415 boolean match1(Matcher matcher, int i, int j, CharSequence seq) { 4416 for (;;) { 4417 // Try finishing match without consuming any more 4418 if (next.match(matcher, i, seq)) 4419 return true; 4420 // At the maximum, no match found 4421 if (j >= cmax) 4422 return false; 4423 // Okay, must try one more atom 4424 if (!atom.match(matcher, i, seq)) 4425 return false; 4426 // If we haven't moved forward then must break out 4427 if (i == matcher.last) 4428 return false; 4429 // Move up index and number matched 4430 i = matcher.last; 4431 j++; 4432 } 4433 } 4434 boolean match2(Matcher matcher, int i, int j, CharSequence seq) { 4435 for (; j < cmax; j++) { 4436 if (!atom.match(matcher, i, seq)) 4437 break; 4438 if (i == matcher.last) 4439 break; 4440 i = matcher.last; 4441 } 4442 return next.match(matcher, i, seq); 4443 } 4444 boolean study(TreeInfo info) { 4445 // Save original info 4446 int minL = info.minLength; 4447 int maxL = info.maxLength; 4448 boolean maxV = info.maxValid; 4449 boolean detm = info.deterministic; 4450 info.reset(); 4451 4452 atom.study(info); 4453 4454 int temp = info.minLength * cmin + minL; 4455 if (temp < minL) { 4456 temp = 0xFFFFFFF; // arbitrary large number 4457 } 4458 info.minLength = temp; 4459 4460 if (maxV & info.maxValid) { 4461 temp = info.maxLength * cmax + maxL; 4462 info.maxLength = temp; 4463 if (temp < maxL) { 4464 info.maxValid = false; 4465 } 4466 } else { 4467 info.maxValid = false; 4468 } 4469 4470 if (info.deterministic && cmin == cmax) 4471 info.deterministic = detm; 4472 else 4473 info.deterministic = false; 4474 return next.study(info); 4475 } 4476 } 4477 4478 /** 4479 * Handles the curly-brace style repetition with a specified minimum and 4480 * maximum occurrences in deterministic cases. This is an iterative 4481 * optimization over the Prolog and Loop system which would handle this 4482 * in a recursive way. The * quantifier is handled as a special case. 4483 * If capture is true then this class saves group settings and ensures 4484 * that groups are unset when backing off of a group match. 4485 */ 4486 static final class GroupCurly extends Node { 4487 Node atom; 4488 Qtype type; 4489 int cmin; 4490 int cmax; 4491 int localIndex; 4492 int groupIndex; 4493 boolean capture; 4494 4495 GroupCurly(Node node, int cmin, int cmax, Qtype type, int local, 4496 int group, boolean capture) { 4497 this.atom = node; 4498 this.type = type; 4499 this.cmin = cmin; 4500 this.cmax = cmax; 4501 this.localIndex = local; 4502 this.groupIndex = group; 4503 this.capture = capture; 4504 } 4505 boolean match(Matcher matcher, int i, CharSequence seq) { 4506 int[] groups = matcher.groups; 4507 int[] locals = matcher.locals; 4508 int save0 = locals[localIndex]; 4509 int save1 = 0; 4510 int save2 = 0; 4511 4512 if (capture) { 4513 save1 = groups[groupIndex]; 4514 save2 = groups[groupIndex+1]; 4515 } 4516 4517 // Notify GroupTail there is no need to setup group info 4518 // because it will be set here 4519 locals[localIndex] = -1; 4520 4521 boolean ret = true; 4522 for (int j = 0; j < cmin; j++) { 4523 if (atom.match(matcher, i, seq)) { 4524 if (capture) { 4525 groups[groupIndex] = i; 4526 groups[groupIndex+1] = matcher.last; 4527 } 4528 i = matcher.last; 4529 } else { 4530 ret = false; 4531 break; 4532 } 4533 } 4534 if (ret) { 4535 if (type == Qtype.GREEDY) { 4536 ret = match0(matcher, i, cmin, seq); 4537 } else if (type == Qtype.LAZY) { 4538 ret = match1(matcher, i, cmin, seq); 4539 } else { 4540 ret = match2(matcher, i, cmin, seq); 4541 } 4542 } 4543 if (!ret) { 4544 locals[localIndex] = save0; 4545 if (capture) { 4546 groups[groupIndex] = save1; 4547 groups[groupIndex+1] = save2; 4548 } 4549 } 4550 return ret; 4551 } 4552 // Aggressive group match 4553 boolean match0(Matcher matcher, int i, int j, CharSequence seq) { 4554 // don't back off passing the starting "j" 4555 int min = j; 4556 int[] groups = matcher.groups; 4557 int save0 = 0; 4558 int save1 = 0; 4559 if (capture) { 4560 save0 = groups[groupIndex]; 4561 save1 = groups[groupIndex+1]; 4562 } 4563 for (;;) { 4564 if (j >= cmax) 4565 break; 4566 if (!atom.match(matcher, i, seq)) 4567 break; 4568 int k = matcher.last - i; 4569 if (k <= 0) { 4570 if (capture) { 4571 groups[groupIndex] = i; 4572 groups[groupIndex+1] = i + k; 4573 } 4574 i = i + k; 4575 break; 4576 } 4577 for (;;) { 4578 if (capture) { 4579 groups[groupIndex] = i; 4580 groups[groupIndex+1] = i + k; 4581 } 4582 i = i + k; 4583 if (++j >= cmax) 4584 break; 4585 if (!atom.match(matcher, i, seq)) 4586 break; 4587 if (i + k != matcher.last) { 4588 if (match0(matcher, i, j, seq)) 4589 return true; 4590 break; 4591 } 4592 } 4593 while (j > min) { 4594 if (next.match(matcher, i, seq)) { 4595 if (capture) { 4596 groups[groupIndex+1] = i; 4597 groups[groupIndex] = i - k; 4598 } 4599 return true; 4600 } 4601 // backing off 4602 i = i - k; 4603 if (capture) { 4604 groups[groupIndex+1] = i; 4605 groups[groupIndex] = i - k; 4606 } 4607 j--; 4608 4609 } 4610 break; 4611 } 4612 if (capture) { 4613 groups[groupIndex] = save0; 4614 groups[groupIndex+1] = save1; 4615 } 4616 return next.match(matcher, i, seq); 4617 } 4618 // Reluctant matching 4619 boolean match1(Matcher matcher, int i, int j, CharSequence seq) { 4620 for (;;) { 4621 if (next.match(matcher, i, seq)) 4622 return true; 4623 if (j >= cmax) 4624 return false; 4625 if (!atom.match(matcher, i, seq)) 4626 return false; 4627 if (i == matcher.last) 4628 return false; 4629 if (capture) { 4630 matcher.groups[groupIndex] = i; 4631 matcher.groups[groupIndex+1] = matcher.last; 4632 } 4633 i = matcher.last; 4634 j++; 4635 } 4636 } 4637 // Possessive matching 4638 boolean match2(Matcher matcher, int i, int j, CharSequence seq) { 4639 for (; j < cmax; j++) { 4640 if (!atom.match(matcher, i, seq)) { 4641 break; 4642 } 4643 if (capture) { 4644 matcher.groups[groupIndex] = i; 4645 matcher.groups[groupIndex+1] = matcher.last; 4646 } 4647 if (i == matcher.last) { 4648 break; 4649 } 4650 i = matcher.last; 4651 } 4652 return next.match(matcher, i, seq); 4653 } 4654 boolean study(TreeInfo info) { 4655 // Save original info 4656 int minL = info.minLength; 4657 int maxL = info.maxLength; 4658 boolean maxV = info.maxValid; 4659 boolean detm = info.deterministic; 4660 info.reset(); 4661 4662 atom.study(info); 4663 4664 int temp = info.minLength * cmin + minL; 4665 if (temp < minL) { 4666 temp = 0xFFFFFFF; // Arbitrary large number 4667 } 4668 info.minLength = temp; 4669 4670 if (maxV & info.maxValid) { 4671 temp = info.maxLength * cmax + maxL; 4672 info.maxLength = temp; 4673 if (temp < maxL) { 4674 info.maxValid = false; 4675 } 4676 } else { 4677 info.maxValid = false; 4678 } 4679 4680 if (info.deterministic && cmin == cmax) { 4681 info.deterministic = detm; 4682 } else { 4683 info.deterministic = false; 4684 } 4685 return next.study(info); 4686 } 4687 } 4688 4689 /** 4690 * A Guard node at the end of each atom node in a Branch. It 4691 * serves the purpose of chaining the "match" operation to 4692 * "next" but not the "study", so we can collect the TreeInfo 4693 * of each atom node without including the TreeInfo of the 4694 * "next". 4695 */ 4696 static final class BranchConn extends Node { 4697 BranchConn() {}; 4698 boolean match(Matcher matcher, int i, CharSequence seq) { 4699 return next.match(matcher, i, seq); 4700 } 4701 boolean study(TreeInfo info) { 4702 return info.deterministic; 4703 } 4704 } 4705 4706 /** 4707 * Handles the branching of alternations. Note this is also used for 4708 * the ? quantifier to branch between the case where it matches once 4709 * and where it does not occur. 4710 */ 4711 static final class Branch extends Node { 4712 Node[] atoms = new Node[2]; 4713 int size = 2; 4714 Node conn; 4715 Branch(Node first, Node second, Node branchConn) { 4716 conn = branchConn; 4717 atoms[0] = first; 4718 atoms[1] = second; 4719 } 4720 4721 void add(Node node) { 4722 if (size >= atoms.length) { 4723 Node[] tmp = new Node[atoms.length*2]; 4724 System.arraycopy(atoms, 0, tmp, 0, atoms.length); 4725 atoms = tmp; 4726 } 4727 atoms[size++] = node; 4728 } 4729 4730 boolean match(Matcher matcher, int i, CharSequence seq) { 4731 for (int n = 0; n < size; n++) { 4732 if (atoms[n] == null) { 4733 if (conn.next.match(matcher, i, seq)) 4734 return true; 4735 } else if (atoms[n].match(matcher, i, seq)) { 4736 return true; 4737 } 4738 } 4739 return false; 4740 } 4741 4742 boolean study(TreeInfo info) { 4743 int minL = info.minLength; 4744 int maxL = info.maxLength; 4745 boolean maxV = info.maxValid; 4746 4747 int minL2 = Integer.MAX_VALUE; //arbitrary large enough num 4748 int maxL2 = -1; 4749 for (int n = 0; n < size; n++) { 4750 info.reset(); 4751 if (atoms[n] != null) 4752 atoms[n].study(info); 4753 minL2 = Math.min(minL2, info.minLength); 4754 maxL2 = Math.max(maxL2, info.maxLength); 4755 maxV = (maxV & info.maxValid); 4756 } 4757 4758 minL += minL2; 4759 maxL += maxL2; 4760 4761 info.reset(); 4762 conn.next.study(info); 4763 4764 info.minLength += minL; 4765 info.maxLength += maxL; 4766 info.maxValid &= maxV; 4767 info.deterministic = false; 4768 return false; 4769 } 4770 } 4771 4772 /** 4773 * The GroupHead saves the location where the group begins in the locals 4774 * and restores them when the match is done. 4775 * 4776 * The matchRef is used when a reference to this group is accessed later 4777 * in the expression. The locals will have a negative value in them to 4778 * indicate that we do not want to unset the group if the reference 4779 * doesn't match. 4780 */ 4781 static final class GroupHead extends Node { 4782 int localIndex; 4783 GroupTail tail; // for debug/print only, match does not need to know 4784 GroupHead(int localCount) { 4785 localIndex = localCount; 4786 } 4787 boolean match(Matcher matcher, int i, CharSequence seq) { 4788 int save = matcher.locals[localIndex]; 4789 matcher.locals[localIndex] = i; 4790 boolean ret = next.match(matcher, i, seq); 4791 matcher.locals[localIndex] = save; 4792 return ret; 4793 } 4794 boolean matchRef(Matcher matcher, int i, CharSequence seq) { 4795 int save = matcher.locals[localIndex]; 4796 matcher.locals[localIndex] = ~i; // HACK 4797 boolean ret = next.match(matcher, i, seq); 4798 matcher.locals[localIndex] = save; 4799 return ret; 4800 } 4801 } 4802 4803 /** 4804 * Recursive reference to a group in the regular expression. It calls 4805 * matchRef because if the reference fails to match we would not unset 4806 * the group. 4807 */ 4808 static final class GroupRef extends Node { 4809 GroupHead head; 4810 GroupRef(GroupHead head) { 4811 this.head = head; 4812 } 4813 boolean match(Matcher matcher, int i, CharSequence seq) { 4814 return head.matchRef(matcher, i, seq) 4815 && next.match(matcher, matcher.last, seq); 4816 } 4817 boolean study(TreeInfo info) { 4818 info.maxValid = false; 4819 info.deterministic = false; 4820 return next.study(info); 4821 } 4822 } 4823 4824 /** 4825 * The GroupTail handles the setting of group beginning and ending 4826 * locations when groups are successfully matched. It must also be able to 4827 * unset groups that have to be backed off of. 4828 * 4829 * The GroupTail node is also used when a previous group is referenced, 4830 * and in that case no group information needs to be set. 4831 */ 4832 static final class GroupTail extends Node { 4833 int localIndex; 4834 int groupIndex; 4835 GroupTail(int localCount, int groupCount) { 4836 localIndex = localCount; 4837 groupIndex = groupCount + groupCount; 4838 } 4839 boolean match(Matcher matcher, int i, CharSequence seq) { 4840 int tmp = matcher.locals[localIndex]; 4841 if (tmp >= 0) { // This is the normal group case. 4842 // Save the group so we can unset it if it 4843 // backs off of a match. 4844 int groupStart = matcher.groups[groupIndex]; 4845 int groupEnd = matcher.groups[groupIndex+1]; 4846 4847 matcher.groups[groupIndex] = tmp; 4848 matcher.groups[groupIndex+1] = i; 4849 if (next.match(matcher, i, seq)) { 4850 return true; 4851 } 4852 matcher.groups[groupIndex] = groupStart; 4853 matcher.groups[groupIndex+1] = groupEnd; 4854 return false; 4855 } else { 4856 // This is a group reference case. We don't need to save any 4857 // group info because it isn't really a group. 4858 matcher.last = i; 4859 return true; 4860 } 4861 } 4862 } 4863 4864 /** 4865 * This sets up a loop to handle a recursive quantifier structure. 4866 */ 4867 static final class Prolog extends Node { 4868 Loop loop; 4869 Prolog(Loop loop) { 4870 this.loop = loop; 4871 } 4872 boolean match(Matcher matcher, int i, CharSequence seq) { 4873 return loop.matchInit(matcher, i, seq); 4874 } 4875 boolean study(TreeInfo info) { 4876 return loop.study(info); 4877 } 4878 } 4879 4880 /** 4881 * Handles the repetition count for a greedy Curly. The matchInit 4882 * is called from the Prolog to save the index of where the group 4883 * beginning is stored. A zero length group check occurs in the 4884 * normal match but is skipped in the matchInit. 4885 */ 4886 static class Loop extends Node { 4887 Node body; 4888 int countIndex; // local count index in matcher locals 4889 int beginIndex; // group beginning index 4890 int cmin, cmax; 4891 int posIndex; 4892 Loop(int countIndex, int beginIndex) { 4893 this.countIndex = countIndex; 4894 this.beginIndex = beginIndex; 4895 this.posIndex = -1; 4896 } 4897 boolean match(Matcher matcher, int i, CharSequence seq) { 4898 // Avoid infinite loop in zero-length case. 4899 if (i > matcher.locals[beginIndex]) { 4900 int count = matcher.locals[countIndex]; 4901 4902 // This block is for before we reach the minimum 4903 // iterations required for the loop to match 4904 if (count < cmin) { 4905 matcher.locals[countIndex] = count + 1; 4906 boolean b = body.match(matcher, i, seq); 4907 // If match failed we must backtrack, so 4908 // the loop count should NOT be incremented 4909 if (!b) 4910 matcher.locals[countIndex] = count; 4911 // Return success or failure since we are under 4912 // minimum 4913 return b; 4914 } 4915 // This block is for after we have the minimum 4916 // iterations required for the loop to match 4917 if (count < cmax) { 4918 // Let's check if we have already tried and failed 4919 // at this starting position "i" in the past. 4920 // If yes, then just return false wihtout trying 4921 // again, to stop the exponential backtracking. 4922 if (posIndex != -1 && 4923 matcher.localsPos[posIndex].contains(i)) { 4924 return next.match(matcher, i, seq); 4925 } 4926 matcher.locals[countIndex] = count + 1; 4927 boolean b = body.match(matcher, i, seq); 4928 // If match failed we must backtrack, so 4929 // the loop count should NOT be incremented 4930 if (b) 4931 return true; 4932 matcher.locals[countIndex] = count; 4933 // save the failed position 4934 if (posIndex != -1) { 4935 matcher.localsPos[posIndex].add(i); 4936 } 4937 } 4938 } 4939 return next.match(matcher, i, seq); 4940 } 4941 boolean matchInit(Matcher matcher, int i, CharSequence seq) { 4942 int save = matcher.locals[countIndex]; 4943 boolean ret = false; 4944 if (posIndex != -1 && matcher.localsPos[posIndex] == null) { 4945 matcher.localsPos[posIndex] = new IntHashSet(); 4946 } 4947 if (0 < cmin) { 4948 matcher.locals[countIndex] = 1; 4949 ret = body.match(matcher, i, seq); 4950 } else if (0 < cmax) { 4951 matcher.locals[countIndex] = 1; 4952 ret = body.match(matcher, i, seq); 4953 if (ret == false) 4954 ret = next.match(matcher, i, seq); 4955 } else { 4956 ret = next.match(matcher, i, seq); 4957 } 4958 matcher.locals[countIndex] = save; 4959 return ret; 4960 } 4961 boolean study(TreeInfo info) { 4962 info.maxValid = false; 4963 info.deterministic = false; 4964 return false; 4965 } 4966 } 4967 4968 /** 4969 * Handles the repetition count for a reluctant Curly. The matchInit 4970 * is called from the Prolog to save the index of where the group 4971 * beginning is stored. A zero length group check occurs in the 4972 * normal match but is skipped in the matchInit. 4973 */ 4974 static final class LazyLoop extends Loop { 4975 LazyLoop(int countIndex, int beginIndex) { 4976 super(countIndex, beginIndex); 4977 } 4978 boolean match(Matcher matcher, int i, CharSequence seq) { 4979 // Check for zero length group 4980 if (i > matcher.locals[beginIndex]) { 4981 int count = matcher.locals[countIndex]; 4982 if (count < cmin) { 4983 matcher.locals[countIndex] = count + 1; 4984 boolean result = body.match(matcher, i, seq); 4985 // If match failed we must backtrack, so 4986 // the loop count should NOT be incremented 4987 if (!result) 4988 matcher.locals[countIndex] = count; 4989 return result; 4990 } 4991 if (next.match(matcher, i, seq)) 4992 return true; 4993 if (count < cmax) { 4994 matcher.locals[countIndex] = count + 1; 4995 boolean result = body.match(matcher, i, seq); 4996 // If match failed we must backtrack, so 4997 // the loop count should NOT be incremented 4998 if (!result) 4999 matcher.locals[countIndex] = count; 5000 return result; 5001 } 5002 return false; 5003 } 5004 return next.match(matcher, i, seq); 5005 } 5006 boolean matchInit(Matcher matcher, int i, CharSequence seq) { 5007 int save = matcher.locals[countIndex]; 5008 boolean ret = false; 5009 if (0 < cmin) { 5010 matcher.locals[countIndex] = 1; 5011 ret = body.match(matcher, i, seq); 5012 } else if (next.match(matcher, i, seq)) { 5013 ret = true; 5014 } else if (0 < cmax) { 5015 matcher.locals[countIndex] = 1; 5016 ret = body.match(matcher, i, seq); 5017 } 5018 matcher.locals[countIndex] = save; 5019 return ret; 5020 } 5021 boolean study(TreeInfo info) { 5022 info.maxValid = false; 5023 info.deterministic = false; 5024 return false; 5025 } 5026 } 5027 5028 /** 5029 * Refers to a group in the regular expression. Attempts to match 5030 * whatever the group referred to last matched. 5031 */ 5032 static class BackRef extends Node { 5033 int groupIndex; 5034 BackRef(int groupCount) { 5035 super(); 5036 groupIndex = groupCount + groupCount; 5037 } 5038 boolean match(Matcher matcher, int i, CharSequence seq) { 5039 int j = matcher.groups[groupIndex]; 5040 int k = matcher.groups[groupIndex+1]; 5041 5042 int groupSize = k - j; 5043 // If the referenced group didn't match, neither can this 5044 if (j < 0) 5045 return false; 5046 5047 // If there isn't enough input left no match 5048 if (i + groupSize > matcher.to) { 5049 matcher.hitEnd = true; 5050 return false; 5051 } 5052 // Check each new char to make sure it matches what the group 5053 // referenced matched last time around 5054 for (int index=0; index<groupSize; index++) 5055 if (seq.charAt(i+index) != seq.charAt(j+index)) 5056 return false; 5057 5058 return next.match(matcher, i+groupSize, seq); 5059 } 5060 boolean study(TreeInfo info) { 5061 info.maxValid = false; 5062 return next.study(info); 5063 } 5064 } 5065 5066 static class CIBackRef extends Node { 5067 int groupIndex; 5068 boolean doUnicodeCase; 5069 CIBackRef(int groupCount, boolean doUnicodeCase) { 5070 super(); 5071 groupIndex = groupCount + groupCount; 5072 this.doUnicodeCase = doUnicodeCase; 5073 } 5074 boolean match(Matcher matcher, int i, CharSequence seq) { 5075 int j = matcher.groups[groupIndex]; 5076 int k = matcher.groups[groupIndex+1]; 5077 5078 int groupSize = k - j; 5079 5080 // If the referenced group didn't match, neither can this 5081 if (j < 0) 5082 return false; 5083 5084 // If there isn't enough input left no match 5085 if (i + groupSize > matcher.to) { 5086 matcher.hitEnd = true; 5087 return false; 5088 } 5089 5090 // Check each new char to make sure it matches what the group 5091 // referenced matched last time around 5092 int x = i; 5093 for (int index=0; index<groupSize; index++) { 5094 int c1 = Character.codePointAt(seq, x); 5095 int c2 = Character.codePointAt(seq, j); 5096 if (c1 != c2) { 5097 if (doUnicodeCase) { 5098 int cc1 = Character.toUpperCase(c1); 5099 int cc2 = Character.toUpperCase(c2); 5100 if (cc1 != cc2 && 5101 Character.toLowerCase(cc1) != 5102 Character.toLowerCase(cc2)) 5103 return false; 5104 } else { 5105 if (ASCII.toLower(c1) != ASCII.toLower(c2)) 5106 return false; 5107 } 5108 } 5109 x += Character.charCount(c1); 5110 j += Character.charCount(c2); 5111 } 5112 5113 return next.match(matcher, i+groupSize, seq); 5114 } 5115 boolean study(TreeInfo info) { 5116 info.maxValid = false; 5117 return next.study(info); 5118 } 5119 } 5120 5121 /** 5122 * Searches until the next instance of its atom. This is useful for 5123 * finding the atom efficiently without passing an instance of it 5124 * (greedy problem) and without a lot of wasted search time (reluctant 5125 * problem). 5126 */ 5127 static final class First extends Node { 5128 Node atom; 5129 First(Node node) { 5130 this.atom = BnM.optimize(node); 5131 } 5132 boolean match(Matcher matcher, int i, CharSequence seq) { 5133 if (atom instanceof BnM) { 5134 return atom.match(matcher, i, seq) 5135 && next.match(matcher, matcher.last, seq); 5136 } 5137 for (;;) { 5138 if (i > matcher.to) { 5139 matcher.hitEnd = true; 5140 return false; 5141 } 5142 if (atom.match(matcher, i, seq)) { 5143 return next.match(matcher, matcher.last, seq); 5144 } 5145 i += countChars(seq, i, 1); 5146 matcher.first++; 5147 } 5148 } 5149 boolean study(TreeInfo info) { 5150 atom.study(info); 5151 info.maxValid = false; 5152 info.deterministic = false; 5153 return next.study(info); 5154 } 5155 } 5156 5157 static final class Conditional extends Node { 5158 Node cond, yes, not; 5159 Conditional(Node cond, Node yes, Node not) { 5160 this.cond = cond; 5161 this.yes = yes; 5162 this.not = not; 5163 } 5164 boolean match(Matcher matcher, int i, CharSequence seq) { 5165 if (cond.match(matcher, i, seq)) { 5166 return yes.match(matcher, i, seq); 5167 } else { 5168 return not.match(matcher, i, seq); 5169 } 5170 } 5171 boolean study(TreeInfo info) { 5172 int minL = info.minLength; 5173 int maxL = info.maxLength; 5174 boolean maxV = info.maxValid; 5175 info.reset(); 5176 yes.study(info); 5177 5178 int minL2 = info.minLength; 5179 int maxL2 = info.maxLength; 5180 boolean maxV2 = info.maxValid; 5181 info.reset(); 5182 not.study(info); 5183 5184 info.minLength = minL + Math.min(minL2, info.minLength); 5185 info.maxLength = maxL + Math.max(maxL2, info.maxLength); 5186 info.maxValid = (maxV & maxV2 & info.maxValid); 5187 info.deterministic = false; 5188 return next.study(info); 5189 } 5190 } 5191 5192 /** 5193 * Zero width positive lookahead. 5194 */ 5195 static final class Pos extends Node { 5196 Node cond; 5197 Pos(Node cond) { 5198 this.cond = cond; 5199 } 5200 boolean match(Matcher matcher, int i, CharSequence seq) { 5201 int savedTo = matcher.to; 5202 boolean conditionMatched = false; 5203 5204 // Relax transparent region boundaries for lookahead 5205 if (matcher.transparentBounds) 5206 matcher.to = matcher.getTextLength(); 5207 try { 5208 conditionMatched = cond.match(matcher, i, seq); 5209 } finally { 5210 // Reinstate region boundaries 5211 matcher.to = savedTo; 5212 } 5213 return conditionMatched && next.match(matcher, i, seq); 5214 } 5215 } 5216 5217 /** 5218 * Zero width negative lookahead. 5219 */ 5220 static final class Neg extends Node { 5221 Node cond; 5222 Neg(Node cond) { 5223 this.cond = cond; 5224 } 5225 boolean match(Matcher matcher, int i, CharSequence seq) { 5226 int savedTo = matcher.to; 5227 boolean conditionMatched = false; 5228 5229 // Relax transparent region boundaries for lookahead 5230 if (matcher.transparentBounds) 5231 matcher.to = matcher.getTextLength(); 5232 try { 5233 if (i < matcher.to) { 5234 conditionMatched = !cond.match(matcher, i, seq); 5235 } else { 5236 // If a negative lookahead succeeds then more input 5237 // could cause it to fail! 5238 matcher.requireEnd = true; 5239 conditionMatched = !cond.match(matcher, i, seq); 5240 } 5241 } finally { 5242 // Reinstate region boundaries 5243 matcher.to = savedTo; 5244 } 5245 return conditionMatched && next.match(matcher, i, seq); 5246 } 5247 } 5248 5249 /** 5250 * For use with lookbehinds; matches the position where the lookbehind 5251 * was encountered. 5252 */ 5253 static Node lookbehindEnd = new Node() { 5254 boolean match(Matcher matcher, int i, CharSequence seq) { 5255 return i == matcher.lookbehindTo; 5256 } 5257 }; 5258 5259 /** 5260 * Zero width positive lookbehind. 5261 */ 5262 static class Behind extends Node { 5263 Node cond; 5264 int rmax, rmin; 5265 Behind(Node cond, int rmax, int rmin) { 5266 this.cond = cond; 5267 this.rmax = rmax; 5268 this.rmin = rmin; 5269 } 5270 5271 boolean match(Matcher matcher, int i, CharSequence seq) { 5272 int savedFrom = matcher.from; 5273 boolean conditionMatched = false; 5274 int startIndex = (!matcher.transparentBounds) ? 5275 matcher.from : 0; 5276 int from = Math.max(i - rmax, startIndex); 5277 // Set end boundary 5278 int savedLBT = matcher.lookbehindTo; 5279 matcher.lookbehindTo = i; 5280 // Relax transparent region boundaries for lookbehind 5281 if (matcher.transparentBounds) 5282 matcher.from = 0; 5283 for (int j = i - rmin; !conditionMatched && j >= from; j--) { 5284 conditionMatched = cond.match(matcher, j, seq); 5285 } 5286 matcher.from = savedFrom; 5287 matcher.lookbehindTo = savedLBT; 5288 return conditionMatched && next.match(matcher, i, seq); 5289 } 5290 } 5291 5292 /** 5293 * Zero width positive lookbehind, including supplementary 5294 * characters or unpaired surrogates. 5295 */ 5296 static final class BehindS extends Behind { 5297 BehindS(Node cond, int rmax, int rmin) { 5298 super(cond, rmax, rmin); 5299 } 5300 boolean match(Matcher matcher, int i, CharSequence seq) { 5301 int rmaxChars = countChars(seq, i, -rmax); 5302 int rminChars = countChars(seq, i, -rmin); 5303 int savedFrom = matcher.from; 5304 int startIndex = (!matcher.transparentBounds) ? 5305 matcher.from : 0; 5306 boolean conditionMatched = false; 5307 int from = Math.max(i - rmaxChars, startIndex); 5308 // Set end boundary 5309 int savedLBT = matcher.lookbehindTo; 5310 matcher.lookbehindTo = i; 5311 // Relax transparent region boundaries for lookbehind 5312 if (matcher.transparentBounds) 5313 matcher.from = 0; 5314 5315 for (int j = i - rminChars; 5316 !conditionMatched && j >= from; 5317 j -= j>from ? countChars(seq, j, -1) : 1) { 5318 conditionMatched = cond.match(matcher, j, seq); 5319 } 5320 matcher.from = savedFrom; 5321 matcher.lookbehindTo = savedLBT; 5322 return conditionMatched && next.match(matcher, i, seq); 5323 } 5324 } 5325 5326 /** 5327 * Zero width negative lookbehind. 5328 */ 5329 static class NotBehind extends Node { 5330 Node cond; 5331 int rmax, rmin; 5332 NotBehind(Node cond, int rmax, int rmin) { 5333 this.cond = cond; 5334 this.rmax = rmax; 5335 this.rmin = rmin; 5336 } 5337 5338 boolean match(Matcher matcher, int i, CharSequence seq) { 5339 int savedLBT = matcher.lookbehindTo; 5340 int savedFrom = matcher.from; 5341 boolean conditionMatched = false; 5342 int startIndex = (!matcher.transparentBounds) ? 5343 matcher.from : 0; 5344 int from = Math.max(i - rmax, startIndex); 5345 matcher.lookbehindTo = i; 5346 // Relax transparent region boundaries for lookbehind 5347 if (matcher.transparentBounds) 5348 matcher.from = 0; 5349 for (int j = i - rmin; !conditionMatched && j >= from; j--) { 5350 conditionMatched = cond.match(matcher, j, seq); 5351 } 5352 // Reinstate region boundaries 5353 matcher.from = savedFrom; 5354 matcher.lookbehindTo = savedLBT; 5355 return !conditionMatched && next.match(matcher, i, seq); 5356 } 5357 } 5358 5359 /** 5360 * Zero width negative lookbehind, including supplementary 5361 * characters or unpaired surrogates. 5362 */ 5363 static final class NotBehindS extends NotBehind { 5364 NotBehindS(Node cond, int rmax, int rmin) { 5365 super(cond, rmax, rmin); 5366 } 5367 boolean match(Matcher matcher, int i, CharSequence seq) { 5368 int rmaxChars = countChars(seq, i, -rmax); 5369 int rminChars = countChars(seq, i, -rmin); 5370 int savedFrom = matcher.from; 5371 int savedLBT = matcher.lookbehindTo; 5372 boolean conditionMatched = false; 5373 int startIndex = (!matcher.transparentBounds) ? 5374 matcher.from : 0; 5375 int from = Math.max(i - rmaxChars, startIndex); 5376 matcher.lookbehindTo = i; 5377 // Relax transparent region boundaries for lookbehind 5378 if (matcher.transparentBounds) 5379 matcher.from = 0; 5380 for (int j = i - rminChars; 5381 !conditionMatched && j >= from; 5382 j -= j>from ? countChars(seq, j, -1) : 1) { 5383 conditionMatched = cond.match(matcher, j, seq); 5384 } 5385 //Reinstate region boundaries 5386 matcher.from = savedFrom; 5387 matcher.lookbehindTo = savedLBT; 5388 return !conditionMatched && next.match(matcher, i, seq); 5389 } 5390 } 5391 5392 /** 5393 * Handles word boundaries. Includes a field to allow this one class to 5394 * deal with the different types of word boundaries we can match. The word 5395 * characters include underscores, letters, and digits. Non spacing marks 5396 * can are also part of a word if they have a base character, otherwise 5397 * they are ignored for purposes of finding word boundaries. 5398 */ 5399 static final class Bound extends Node { 5400 static int LEFT = 0x1; 5401 static int RIGHT= 0x2; 5402 static int BOTH = 0x3; 5403 static int NONE = 0x4; 5404 int type; 5405 boolean useUWORD; 5406 Bound(int n, boolean useUWORD) { 5407 type = n; 5408 this.useUWORD = useUWORD; 5409 } 5410 5411 boolean isWord(int ch) { 5412 return useUWORD ? CharPredicates.WORD().is(ch) 5413 : (ch == '_' || Character.isLetterOrDigit(ch)); 5414 } 5415 5416 int check(Matcher matcher, int i, CharSequence seq) { 5417 int ch; 5418 boolean left = false; 5419 int startIndex = matcher.from; 5420 int endIndex = matcher.to; 5421 if (matcher.transparentBounds) { 5422 startIndex = 0; 5423 endIndex = matcher.getTextLength(); 5424 } 5425 if (i > startIndex) { 5426 ch = Character.codePointBefore(seq, i); 5427 left = (isWord(ch) || 5428 ((Character.getType(ch) == Character.NON_SPACING_MARK) 5429 && hasBaseCharacter(matcher, i-1, seq))); 5430 } 5431 boolean right = false; 5432 if (i < endIndex) { 5433 ch = Character.codePointAt(seq, i); 5434 right = (isWord(ch) || 5435 ((Character.getType(ch) == Character.NON_SPACING_MARK) 5436 && hasBaseCharacter(matcher, i, seq))); 5437 } else { 5438 // Tried to access char past the end 5439 matcher.hitEnd = true; 5440 // The addition of another char could wreck a boundary 5441 matcher.requireEnd = true; 5442 } 5443 return ((left ^ right) ? (right ? LEFT : RIGHT) : NONE); 5444 } 5445 boolean match(Matcher matcher, int i, CharSequence seq) { 5446 return (check(matcher, i, seq) & type) > 0 5447 && next.match(matcher, i, seq); 5448 } 5449 } 5450 5451 /** 5452 * Non spacing marks only count as word characters in bounds calculations 5453 * if they have a base character. 5454 */ 5455 private static boolean hasBaseCharacter(Matcher matcher, int i, 5456 CharSequence seq) 5457 { 5458 int start = (!matcher.transparentBounds) ? 5459 matcher.from : 0; 5460 for (int x=i; x >= start; x--) { 5461 int ch = Character.codePointAt(seq, x); 5462 if (Character.isLetterOrDigit(ch)) 5463 return true; 5464 if (Character.getType(ch) == Character.NON_SPACING_MARK) 5465 continue; 5466 return false; 5467 } 5468 return false; 5469 } 5470 5471 /** 5472 * Attempts to match a slice in the input using the Boyer-Moore string 5473 * matching algorithm. The algorithm is based on the idea that the 5474 * pattern can be shifted farther ahead in the search text if it is 5475 * matched right to left. 5476 * <p> 5477 * The pattern is compared to the input one character at a time, from 5478 * the rightmost character in the pattern to the left. If the characters 5479 * all match the pattern has been found. If a character does not match, 5480 * the pattern is shifted right a distance that is the maximum of two 5481 * functions, the bad character shift and the good suffix shift. This 5482 * shift moves the attempted match position through the input more 5483 * quickly than a naive one position at a time check. 5484 * <p> 5485 * The bad character shift is based on the character from the text that 5486 * did not match. If the character does not appear in the pattern, the 5487 * pattern can be shifted completely beyond the bad character. If the 5488 * character does occur in the pattern, the pattern can be shifted to 5489 * line the pattern up with the next occurrence of that character. 5490 * <p> 5491 * The good suffix shift is based on the idea that some subset on the right 5492 * side of the pattern has matched. When a bad character is found, the 5493 * pattern can be shifted right by the pattern length if the subset does 5494 * not occur again in pattern, or by the amount of distance to the 5495 * next occurrence of the subset in the pattern. 5496 * 5497 * Boyer-Moore search methods adapted from code by Amy Yu. 5498 */ 5499 static class BnM extends Node { 5500 int[] buffer; 5501 int[] lastOcc; 5502 int[] optoSft; 5503 5504 /** 5505 * Pre calculates arrays needed to generate the bad character 5506 * shift and the good suffix shift. Only the last seven bits 5507 * are used to see if chars match; This keeps the tables small 5508 * and covers the heavily used ASCII range, but occasionally 5509 * results in an aliased match for the bad character shift. 5510 */ 5511 static Node optimize(Node node) { 5512 if (!(node instanceof Slice)) { 5513 return node; 5514 } 5515 5516 int[] src = ((Slice) node).buffer; 5517 int patternLength = src.length; 5518 // The BM algorithm requires a bit of overhead; 5519 // If the pattern is short don't use it, since 5520 // a shift larger than the pattern length cannot 5521 // be used anyway. 5522 if (patternLength < 4) { 5523 return node; 5524 } 5525 int i, j, k; 5526 int[] lastOcc = new int[128]; 5527 int[] optoSft = new int[patternLength]; 5528 // Precalculate part of the bad character shift 5529 // It is a table for where in the pattern each 5530 // lower 7-bit value occurs 5531 for (i = 0; i < patternLength; i++) { 5532 lastOcc[src[i]&0x7F] = i + 1; 5533 } 5534 // Precalculate the good suffix shift 5535 // i is the shift amount being considered 5536NEXT: for (i = patternLength; i > 0; i--) { 5537 // j is the beginning index of suffix being considered 5538 for (j = patternLength - 1; j >= i; j--) { 5539 // Testing for good suffix 5540 if (src[j] == src[j-i]) { 5541 // src[j..len] is a good suffix 5542 optoSft[j-1] = i; 5543 } else { 5544 // No match. The array has already been 5545 // filled up with correct values before. 5546 continue NEXT; 5547 } 5548 } 5549 // This fills up the remaining of optoSft 5550 // any suffix can not have larger shift amount 5551 // then its sub-suffix. Why??? 5552 while (j > 0) { 5553 optoSft[--j] = i; 5554 } 5555 } 5556 // Set the guard value because of unicode compression 5557 optoSft[patternLength-1] = 1; 5558 if (node instanceof SliceS) 5559 return new BnMS(src, lastOcc, optoSft, node.next); 5560 return new BnM(src, lastOcc, optoSft, node.next); 5561 } 5562 BnM(int[] src, int[] lastOcc, int[] optoSft, Node next) { 5563 this.buffer = src; 5564 this.lastOcc = lastOcc; 5565 this.optoSft = optoSft; 5566 this.next = next; 5567 } 5568 boolean match(Matcher matcher, int i, CharSequence seq) { 5569 int[] src = buffer; 5570 int patternLength = src.length; 5571 int last = matcher.to - patternLength; 5572 5573 // Loop over all possible match positions in text 5574NEXT: while (i <= last) { 5575 // Loop over pattern from right to left 5576 for (int j = patternLength - 1; j >= 0; j--) { 5577 int ch = seq.charAt(i+j); 5578 if (ch != src[j]) { 5579 // Shift search to the right by the maximum of the 5580 // bad character shift and the good suffix shift 5581 i += Math.max(j + 1 - lastOcc[ch&0x7F], optoSft[j]); 5582 continue NEXT; 5583 } 5584 } 5585 // Entire pattern matched starting at i 5586 matcher.first = i; 5587 boolean ret = next.match(matcher, i + patternLength, seq); 5588 if (ret) { 5589 matcher.first = i; 5590 matcher.groups[0] = matcher.first; 5591 matcher.groups[1] = matcher.last; 5592 return true; 5593 } 5594 i++; 5595 } 5596 // BnM is only used as the leading node in the unanchored case, 5597 // and it replaced its Start() which always searches to the end 5598 // if it doesn't find what it's looking for, so hitEnd is true. 5599 matcher.hitEnd = true; 5600 return false; 5601 } 5602 boolean study(TreeInfo info) { 5603 info.minLength += buffer.length; 5604 info.maxValid = false; 5605 return next.study(info); 5606 } 5607 } 5608 5609 /** 5610 * Supplementary support version of BnM(). Unpaired surrogates are 5611 * also handled by this class. 5612 */ 5613 static final class BnMS extends BnM { 5614 int lengthInChars; 5615 5616 BnMS(int[] src, int[] lastOcc, int[] optoSft, Node next) { 5617 super(src, lastOcc, optoSft, next); 5618 for (int cp : buffer) { 5619 lengthInChars += Character.charCount(cp); 5620 } 5621 } 5622 boolean match(Matcher matcher, int i, CharSequence seq) { 5623 int[] src = buffer; 5624 int patternLength = src.length; 5625 int last = matcher.to - lengthInChars; 5626 5627 // Loop over all possible match positions in text 5628NEXT: while (i <= last) { 5629 // Loop over pattern from right to left 5630 int ch; 5631 for (int j = countChars(seq, i, patternLength), x = patternLength - 1; 5632 j > 0; j -= Character.charCount(ch), x--) { 5633 ch = Character.codePointBefore(seq, i+j); 5634 if (ch != src[x]) { 5635 // Shift search to the right by the maximum of the 5636 // bad character shift and the good suffix shift 5637 int n = Math.max(x + 1 - lastOcc[ch&0x7F], optoSft[x]); 5638 i += countChars(seq, i, n); 5639 continue NEXT; 5640 } 5641 } 5642 // Entire pattern matched starting at i 5643 matcher.first = i; 5644 boolean ret = next.match(matcher, i + lengthInChars, seq); 5645 if (ret) { 5646 matcher.first = i; 5647 matcher.groups[0] = matcher.first; 5648 matcher.groups[1] = matcher.last; 5649 return true; 5650 } 5651 i += countChars(seq, i, 1); 5652 } 5653 matcher.hitEnd = true; 5654 return false; 5655 } 5656 } 5657 5658 @FunctionalInterface 5659 static interface CharPredicate { 5660 boolean is(int ch); 5661 5662 default CharPredicate and(CharPredicate p) { 5663 return ch -> is(ch) && p.is(ch); 5664 } 5665 default CharPredicate union(CharPredicate p) { 5666 return ch -> is(ch) || p.is(ch); 5667 } 5668 default CharPredicate union(CharPredicate p1, 5669 CharPredicate p2 ) { 5670 return ch -> is(ch) || p1.is(ch) || p2.is(ch); 5671 } 5672 default CharPredicate negate() { 5673 return ch -> !is(ch); 5674 } 5675 } 5676 5677 static interface BmpCharPredicate extends CharPredicate { 5678 5679 default CharPredicate and(CharPredicate p) { 5680 if(p instanceof BmpCharPredicate) 5681 return (BmpCharPredicate)(ch -> is(ch) && p.is(ch)); 5682 return ch -> is(ch) && p.is(ch); 5683 } 5684 default CharPredicate union(CharPredicate p) { 5685 if (p instanceof BmpCharPredicate) 5686 return (BmpCharPredicate)(ch -> is(ch) || p.is(ch)); 5687 return ch -> is(ch) || p.is(ch); 5688 } 5689 static CharPredicate union(CharPredicate... predicates) { 5690 CharPredicate cp = ch -> { 5691 for (CharPredicate p : predicates) { 5692 if (!p.is(ch)) 5693 return false; 5694 } 5695 return true; 5696 }; 5697 for (CharPredicate p : predicates) { 5698 if (! (p instanceof BmpCharPredicate)) 5699 return cp; 5700 } 5701 return (BmpCharPredicate)cp; 5702 } 5703 } 5704 5705 /** 5706 * matches a Perl vertical whitespace 5707 */ 5708 static BmpCharPredicate VertWS() { 5709 return cp -> (cp >= 0x0A && cp <= 0x0D) || 5710 cp == 0x85 || cp == 0x2028 || cp == 0x2029; 5711 } 5712 5713 /** 5714 * matches a Perl horizontal whitespace 5715 */ 5716 static BmpCharPredicate HorizWS() { 5717 return cp -> 5718 cp == 0x09 || cp == 0x20 || cp == 0xa0 || cp == 0x1680 || 5719 cp == 0x180e || cp >= 0x2000 && cp <= 0x200a || cp == 0x202f || 5720 cp == 0x205f || cp == 0x3000; 5721 } 5722 5723 /** 5724 * for the Unicode category ALL and the dot metacharacter when 5725 * in dotall mode. 5726 */ 5727 static CharPredicate ALL() { 5728 return ch -> true; 5729 } 5730 5731 /** 5732 * for the dot metacharacter when dotall is not enabled. 5733 */ 5734 static CharPredicate DOT() { 5735 return ch -> 5736 (ch != '\n' && ch != '\r' 5737 && (ch|1) != '\u2029' 5738 && ch != '\u0085'); 5739 } 5740 5741 /** 5742 * the dot metacharacter when dotall is not enabled but UNIX_LINES is enabled. 5743 */ 5744 static CharPredicate UNIXDOT() { 5745 return ch -> ch != '\n'; 5746 } 5747 5748 /** 5749 * Indicate that matches a Supplementary Unicode character 5750 */ 5751 static CharPredicate SingleS(int c) { 5752 return ch -> ch == c; 5753 } 5754 5755 /** 5756 * A bmp/optimized predicate of single 5757 */ 5758 static BmpCharPredicate Single(int c) { 5759 return ch -> ch == c; 5760 } 5761 5762 /** 5763 * Case insensitive matches a given BMP character 5764 */ 5765 static BmpCharPredicate SingleI(int lower, int upper) { 5766 return ch -> ch == lower || ch == upper; 5767 } 5768 5769 /** 5770 * Unicode case insensitive matches a given Unicode character 5771 */ 5772 static CharPredicate SingleU(int lower) { 5773 return ch -> lower == ch || 5774 lower == Character.toLowerCase(Character.toUpperCase(ch)); 5775 } 5776 5777 private static boolean inRange(int lower, int ch, int upper) { 5778 return lower <= ch && ch <= upper; 5779 } 5780 5781 /** 5782 * Charactrs within a explicit value range 5783 */ 5784 static CharPredicate Range(int lower, int upper) { 5785 if (upper < Character.MIN_HIGH_SURROGATE || 5786 lower > Character.MAX_HIGH_SURROGATE && 5787 upper < Character.MIN_SUPPLEMENTARY_CODE_POINT) 5788 return (BmpCharPredicate)(ch -> inRange(lower, ch, upper)); 5789 return ch -> inRange(lower, ch, upper); 5790 } 5791 5792 /** 5793 * Charactrs within a explicit value range in a case insensitive manner. 5794 */ 5795 static CharPredicate CIRange(int lower, int upper) { 5796 return ch -> inRange(lower, ch, upper) || 5797 ASCII.isAscii(ch) && 5798 (inRange(lower, ASCII.toUpper(ch), upper) || 5799 inRange(lower, ASCII.toLower(ch), upper)); 5800 } 5801 5802 static CharPredicate CIRangeU(int lower, int upper) { 5803 return ch -> { 5804 if (inRange(lower, ch, upper)) 5805 return true; 5806 int up = Character.toUpperCase(ch); 5807 return inRange(lower, up, upper) || 5808 inRange(lower, Character.toLowerCase(up), upper); 5809 }; 5810 } 5811 5812 /** 5813 * This must be the very first initializer. 5814 */ 5815 static final Node accept = new Node(); 5816 5817 static final Node lastAccept = new LastNode(); 5818 5819 /** 5820 * Creates a predicate which can be used to match a string. 5821 * 5822 * @return The predicate which can be used for matching on a string 5823 * @since 1.8 5824 */ 5825 public Predicate<String> asPredicate() { 5826 return s -> matcher(s).find(); 5827 } 5828 5829 /** 5830 * Creates a stream from the given input sequence around matches of this 5831 * pattern. 5832 * 5833 * <p> The stream returned by this method contains each substring of the 5834 * input sequence that is terminated by another subsequence that matches 5835 * this pattern or is terminated by the end of the input sequence. The 5836 * substrings in the stream are in the order in which they occur in the 5837 * input. Trailing empty strings will be discarded and not encountered in 5838 * the stream. 5839 * 5840 * <p> If this pattern does not match any subsequence of the input then 5841 * the resulting stream has just one element, namely the input sequence in 5842 * string form. 5843 * 5844 * <p> When there is a positive-width match at the beginning of the input 5845 * sequence then an empty leading substring is included at the beginning 5846 * of the stream. A zero-width match at the beginning however never produces 5847 * such empty leading substring. 5848 * 5849 * <p> If the input sequence is mutable, it must remain constant during the 5850 * execution of the terminal stream operation. Otherwise, the result of the 5851 * terminal stream operation is undefined. 5852 * 5853 * @param input 5854 * The character sequence to be split 5855 * 5856 * @return The stream of strings computed by splitting the input 5857 * around matches of this pattern 5858 * @see #split(CharSequence) 5859 * @since 1.8 5860 */ 5861 public Stream<String> splitAsStream(final CharSequence input) { 5862 class MatcherIterator implements Iterator<String> { 5863 private Matcher matcher; 5864 // The start position of the next sub-sequence of input 5865 // when current == input.length there are no more elements 5866 private int current; 5867 // null if the next element, if any, needs to obtained 5868 private String nextElement; 5869 // > 0 if there are N next empty elements 5870 private int emptyElementCount; 5871 5872 public String next() { 5873 if (!hasNext()) 5874 throw new NoSuchElementException(); 5875 5876 if (emptyElementCount == 0) { 5877 String n = nextElement; 5878 nextElement = null; 5879 return n; 5880 } else { 5881 emptyElementCount--; 5882 return ""; 5883 } 5884 } 5885 5886 public boolean hasNext() { 5887 if (matcher == null) { 5888 matcher = matcher(input); 5889 // If the input is an empty string then the result can only be a 5890 // stream of the input. Induce that by setting the empty 5891 // element count to 1 5892 emptyElementCount = input.length() == 0 ? 1 : 0; 5893 } 5894 if (nextElement != null || emptyElementCount > 0) 5895 return true; 5896 5897 if (current == input.length()) 5898 return false; 5899 5900 // Consume the next matching element 5901 // Count sequence of matching empty elements 5902 while (matcher.find()) { 5903 nextElement = input.subSequence(current, matcher.start()).toString(); 5904 current = matcher.end(); 5905 if (!nextElement.isEmpty()) { 5906 return true; 5907 } else if (current > 0) { // no empty leading substring for zero-width 5908 // match at the beginning of the input 5909 emptyElementCount++; 5910 } 5911 } 5912 5913 // Consume last matching element 5914 nextElement = input.subSequence(current, input.length()).toString(); 5915 current = input.length(); 5916 if (!nextElement.isEmpty()) { 5917 return true; 5918 } else { 5919 // Ignore a terminal sequence of matching empty elements 5920 emptyElementCount = 0; 5921 nextElement = null; 5922 return false; 5923 } 5924 } 5925 } 5926 return StreamSupport.stream(Spliterators.spliteratorUnknownSize( 5927 new MatcherIterator(), Spliterator.ORDERED | Spliterator.NONNULL), false); 5928 } 5929} 5930