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