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