1/* 2 * Copyright (C) 2014 The Android Open Source Project 3 * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. 4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 5 * 6 * This code is free software; you can redistribute it and/or modify it 7 * under the terms of the GNU General Public License version 2 only, as 8 * published by the Free Software Foundation. Oracle designates this 9 * particular file as subject to the "Classpath" exception as provided 10 * by Oracle in the LICENSE file that accompanied this code. 11 * 12 * This code is distributed in the hope that it will be useful, but WITHOUT 13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 14 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 15 * version 2 for more details (a copy is included in the LICENSE file that 16 * accompanied this code). 17 * 18 * You should have received a copy of the GNU General Public License version 19 * 2 along with this work; if not, write to the Free Software Foundation, 20 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 21 * 22 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 23 * or visit www.oracle.com if you need additional information or have any 24 * questions. 25 */ 26 27package java.util.regex; 28 29import dalvik.annotation.optimization.ReachabilitySensitive; 30import libcore.util.NativeAllocationRegistry; 31 32import java.util.Iterator; 33import java.util.ArrayList; 34import java.util.NoSuchElementException; 35import java.util.Spliterator; 36import java.util.Spliterators; 37import java.util.function.Predicate; 38import java.util.stream.Stream; 39import java.util.stream.StreamSupport; 40 41import libcore.util.EmptyArray; 42 43// Android-changed: Add min API level of 26 for the named capaturing in javadoc 44/** 45 * A compiled representation of a regular expression. 46 * 47 * <p> A regular expression, specified as a string, must first be compiled into 48 * an instance of this class. The resulting pattern can then be used to create 49 * a {@link Matcher} object that can match arbitrary {@link 50 * java.lang.CharSequence </code>character sequences<code>} against the regular 51 * expression. All of the state involved in performing a match resides in the 52 * matcher, so many matchers can share the same pattern. 53 * 54 * <p> A typical invocation sequence is thus 55 * 56 * <blockquote><pre> 57 * Pattern p = Pattern.{@link #compile compile}("a*b"); 58 * Matcher m = p.{@link #matcher matcher}("aaaaab"); 59 * boolean b = m.{@link Matcher#matches matches}();</pre></blockquote> 60 * 61 * <p> A {@link #matches matches} method is defined by this class as a 62 * convenience for when a regular expression is used just once. This method 63 * compiles an expression and matches an input sequence against it in a single 64 * invocation. The statement 65 * 66 * <blockquote><pre> 67 * boolean b = Pattern.matches("a*b", "aaaaab");</pre></blockquote> 68 * 69 * is equivalent to the three statements above, though for repeated matches it 70 * is less efficient since it does not allow the compiled pattern to be reused. 71 * 72 * <p> Instances of this class are immutable and are safe for use by multiple 73 * concurrent threads. Instances of the {@link Matcher} class are not safe for 74 * such use. 75 * 76 * 77 * <a name="sum"> 78 * <h4> Summary of regular-expression constructs </h4> 79 * 80 * <table border="0" cellpadding="1" cellspacing="0" 81 * summary="Regular expression constructs, and what they match"> 82 * 83 * <tr align="left"> 84 * <th bgcolor="#CCCCFF" align="left" id="construct">Construct</th> 85 * <th bgcolor="#CCCCFF" align="left" id="matches">Matches</th> 86 * </tr> 87 * 88 * <tr><th> </th></tr> 89 * <tr align="left"><th colspan="2" id="characters">Characters</th></tr> 90 * 91 * <tr><td valign="top" headers="construct characters"><i>x</i></td> 92 * <td headers="matches">The character <i>x</i></td></tr> 93 * <tr><td valign="top" headers="construct characters"><tt>\\</tt></td> 94 * <td headers="matches">The backslash character</td></tr> 95 * <tr><td valign="top" headers="construct characters"><tt>\0</tt><i>n</i></td> 96 * <td headers="matches">The character with octal value <tt>0</tt><i>n</i> 97 * (0 <tt><=</tt> <i>n</i> <tt><=</tt> 7)</td></tr> 98 * <tr><td valign="top" headers="construct characters"><tt>\0</tt><i>nn</i></td> 99 * <td headers="matches">The character with octal value <tt>0</tt><i>nn</i> 100 * (0 <tt><=</tt> <i>n</i> <tt><=</tt> 7)</td></tr> 101 * <tr><td valign="top" headers="construct characters"><tt>\0</tt><i>mnn</i></td> 102 * <td headers="matches">The character with octal value <tt>0</tt><i>mnn</i> 103 * (0 <tt><=</tt> <i>m</i> <tt><=</tt> 3, 104 * 0 <tt><=</tt> <i>n</i> <tt><=</tt> 7)</td></tr> 105 * <tr><td valign="top" headers="construct characters"><tt>\x</tt><i>hh</i></td> 106 * <td headers="matches">The character with hexadecimal value <tt>0x</tt><i>hh</i></td></tr> 107 * <tr><td valign="top" headers="construct characters"><tt>\u</tt><i>hhhh</i></td> 108 * <td headers="matches">The character with hexadecimal value <tt>0x</tt><i>hhhh</i></td></tr> 109 * <tr><td valign="top" headers="construct characters"><tt>\x</tt><i>{h...h}</i></td> 110 * <td headers="matches">The character with hexadecimal value <tt>0x</tt><i>h...h</i> 111 * ({@link java.lang.Character#MIN_CODE_POINT Character.MIN_CODE_POINT} 112 * <= <tt>0x</tt><i>h...h</i> <=  113 * {@link java.lang.Character#MAX_CODE_POINT Character.MAX_CODE_POINT})</td></tr> 114 * <tr><td valign="top" headers="matches"><tt>\t</tt></td> 115 * <td headers="matches">The tab character (<tt>'\u0009'</tt>)</td></tr> 116 * <tr><td valign="top" headers="construct characters"><tt>\n</tt></td> 117 * <td headers="matches">The newline (line feed) character (<tt>'\u000A'</tt>)</td></tr> 118 * <tr><td valign="top" headers="construct characters"><tt>\r</tt></td> 119 * <td headers="matches">The carriage-return character (<tt>'\u000D'</tt>)</td></tr> 120 * <tr><td valign="top" headers="construct characters"><tt>\f</tt></td> 121 * <td headers="matches">The form-feed character (<tt>'\u000C'</tt>)</td></tr> 122 * <tr><td valign="top" headers="construct characters"><tt>\a</tt></td> 123 * <td headers="matches">The alert (bell) character (<tt>'\u0007'</tt>)</td></tr> 124 * <tr><td valign="top" headers="construct characters"><tt>\e</tt></td> 125 * <td headers="matches">The escape character (<tt>'\u001B'</tt>)</td></tr> 126 * <tr><td valign="top" headers="construct characters"><tt>\c</tt><i>x</i></td> 127 * <td headers="matches">The control character corresponding to <i>x</i></td></tr> 128 * 129 * <tr><th> </th></tr> 130 * <tr align="left"><th colspan="2" id="classes">Character classes</th></tr> 131 * 132 * <tr><td valign="top" headers="construct classes"><tt>[abc]</tt></td> 133 * <td headers="matches"><tt>a</tt>, <tt>b</tt>, or <tt>c</tt> (simple class)</td></tr> 134 * <tr><td valign="top" headers="construct classes"><tt>[^abc]</tt></td> 135 * <td headers="matches">Any character except <tt>a</tt>, <tt>b</tt>, or <tt>c</tt> (negation)</td></tr> 136 * <tr><td valign="top" headers="construct classes"><tt>[a-zA-Z]</tt></td> 137 * <td headers="matches"><tt>a</tt> through <tt>z</tt> 138 * or <tt>A</tt> through <tt>Z</tt>, inclusive (range)</td></tr> 139 * <tr><td valign="top" headers="construct classes"><tt>[a-d[m-p]]</tt></td> 140 * <td headers="matches"><tt>a</tt> through <tt>d</tt>, 141 * or <tt>m</tt> through <tt>p</tt>: <tt>[a-dm-p]</tt> (union)</td></tr> 142 * <tr><td valign="top" headers="construct classes"><tt>[a-z&&[def]]</tt></td> 143 * <td headers="matches"><tt>d</tt>, <tt>e</tt>, or <tt>f</tt> (intersection)</tr> 144 * <tr><td valign="top" headers="construct classes"><tt>[a-z&&[^bc]]</tt></td> 145 * <td headers="matches"><tt>a</tt> through <tt>z</tt>, 146 * except for <tt>b</tt> and <tt>c</tt>: <tt>[ad-z]</tt> (subtraction)</td></tr> 147 * <tr><td valign="top" headers="construct classes"><tt>[a-z&&[^m-p]]</tt></td> 148 * <td headers="matches"><tt>a</tt> through <tt>z</tt>, 149 * and not <tt>m</tt> through <tt>p</tt>: <tt>[a-lq-z]</tt>(subtraction)</td></tr> 150 * <tr><th> </th></tr> 151 * 152 * <tr align="left"><th colspan="2" id="predef">Predefined character classes</th></tr> 153 * 154 * <tr><td valign="top" headers="construct predef"><tt>.</tt></td> 155 * <td headers="matches">Any character (may or may not match <a href="#lt">line terminators</a>)</td></tr> 156 * <tr><td valign="top" headers="construct predef"><tt>\d</tt></td> 157 * <td headers="matches">A digit: <tt>[0-9]</tt></td></tr> 158 * <tr><td valign="top" headers="construct predef"><tt>\D</tt></td> 159 * <td headers="matches">A non-digit: <tt>[^0-9]</tt></td></tr> 160 * <tr><td valign="top" headers="construct predef"><tt>\s</tt></td> 161 * <td headers="matches">A whitespace character: <tt>[ \t\n\x0B\f\r]</tt></td></tr> 162 * <tr><td valign="top" headers="construct predef"><tt>\S</tt></td> 163 * <td headers="matches">A non-whitespace character: <tt>[^\s]</tt></td></tr> 164 * <tr><td valign="top" headers="construct predef"><tt>\w</tt></td> 165 * <td headers="matches">A word character: <tt>[a-zA-Z_0-9]</tt></td></tr> 166 * <tr><td valign="top" headers="construct predef"><tt>\W</tt></td> 167 * <td headers="matches">A non-word character: <tt>[^\w]</tt></td></tr> 168 * 169 * <tr><th> </th></tr> 170 * <tr align="left"><th colspan="2" id="posix">POSIX character classes</b> (US-ASCII only)<b></th></tr> 171 * 172 * <tr><td valign="top" headers="construct posix"><tt>\p{Lower}</tt></td> 173 * <td headers="matches">A lower-case alphabetic character: <tt>[a-z]</tt></td></tr> 174 * <tr><td valign="top" headers="construct posix"><tt>\p{Upper}</tt></td> 175 * <td headers="matches">An upper-case alphabetic character:<tt>[A-Z]</tt></td></tr> 176 * <tr><td valign="top" headers="construct posix"><tt>\p{ASCII}</tt></td> 177 * <td headers="matches">All ASCII:<tt>[\x00-\x7F]</tt></td></tr> 178 * <tr><td valign="top" headers="construct posix"><tt>\p{Alpha}</tt></td> 179 * <td headers="matches">An alphabetic character:<tt>[\p{Lower}\p{Upper}]</tt></td></tr> 180 * <tr><td valign="top" headers="construct posix"><tt>\p{Digit}</tt></td> 181 * <td headers="matches">A decimal digit: <tt>[0-9]</tt></td></tr> 182 * <tr><td valign="top" headers="construct posix"><tt>\p{Alnum}</tt></td> 183 * <td headers="matches">An alphanumeric character:<tt>[\p{Alpha}\p{Digit}]</tt></td></tr> 184 * <tr><td valign="top" headers="construct posix"><tt>\p{Punct}</tt></td> 185 * <td headers="matches">Punctuation: One of <tt>!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~</tt></td></tr> 186 * <!-- <tt>[\!"#\$%&'\(\)\*\+,\-\./:;\<=\>\?@\[\\\]\^_`\{\|\}~]</tt> 187 * <tt>[\X21-\X2F\X31-\X40\X5B-\X60\X7B-\X7E]</tt> --> 188 * <tr><td valign="top" headers="construct posix"><tt>\p{Graph}</tt></td> 189 * <td headers="matches">A visible character: <tt>[\p{Alnum}\p{Punct}]</tt></td></tr> 190 * <tr><td valign="top" headers="construct posix"><tt>\p{Print}</tt></td> 191 * <td headers="matches">A printable character: <tt>[\p{Graph}\x20]</tt></td></tr> 192 * <tr><td valign="top" headers="construct posix"><tt>\p{Blank}</tt></td> 193 * <td headers="matches">A space or a tab: <tt>[ \t]</tt></td></tr> 194 * <tr><td valign="top" headers="construct posix"><tt>\p{Cntrl}</tt></td> 195 * <td headers="matches">A control character: <tt>[\x00-\x1F\x7F]</tt></td></tr> 196 * <tr><td valign="top" headers="construct posix"><tt>\p{XDigit}</tt></td> 197 * <td headers="matches">A hexadecimal digit: <tt>[0-9a-fA-F]</tt></td></tr> 198 * <tr><td valign="top" headers="construct posix"><tt>\p{Space}</tt></td> 199 * <td headers="matches">A whitespace character: <tt>[ \t\n\x0B\f\r]</tt></td></tr> 200 * 201 * <tr><th> </th></tr> 202 * <tr align="left"><th colspan="2">java.lang.Character classes (simple <a href="#jcc">java character type</a>)</th></tr> 203 * 204 * <tr><td valign="top"><tt>\p{javaLowerCase}</tt></td> 205 * <td>Equivalent to java.lang.Character.isLowerCase()</td></tr> 206 * <tr><td valign="top"><tt>\p{javaUpperCase}</tt></td> 207 * <td>Equivalent to java.lang.Character.isUpperCase()</td></tr> 208 * <tr><td valign="top"><tt>\p{javaWhitespace}</tt></td> 209 * <td>Equivalent to java.lang.Character.isWhitespace()</td></tr> 210 * <tr><td valign="top"><tt>\p{javaMirrored}</tt></td> 211 * <td>Equivalent to java.lang.Character.isMirrored()</td></tr> 212 * 213 * <tr><th> </th></tr> 214 * <tr align="left"><th colspan="2" id="unicode">Classes for Unicode scripts, blocks, categories and binary properties</th></tr> 215 * * <tr><td valign="top" headers="construct unicode"><tt>\p{IsLatin}</tt></td> 216 * <td headers="matches">A Latin script character (<a href="#usc">script</a>)</td></tr> 217 * <tr><td valign="top" headers="construct unicode"><tt>\p{InGreek}</tt></td> 218 * <td headers="matches">A character in the Greek block (<a href="#ubc">block</a>)</td></tr> 219 * <tr><td valign="top" headers="construct unicode"><tt>\p{Lu}</tt></td> 220 * <td headers="matches">An uppercase letter (<a href="#ucc">category</a>)</td></tr> 221 * <tr><td valign="top" headers="construct unicode"><tt>\p{IsAlphabetic}</tt></td> 222 * <td headers="matches">An alphabetic character (<a href="#ubpc">binary property</a>)</td></tr> 223 * <tr><td valign="top" headers="construct unicode"><tt>\p{Sc}</tt></td> 224 * <td headers="matches">A currency symbol</td></tr> 225 * <tr><td valign="top" headers="construct unicode"><tt>\P{InGreek}</tt></td> 226 * <td headers="matches">Any character except one in the Greek block (negation)</td></tr> 227 * <tr><td valign="top" headers="construct unicode"><tt>[\p{L}&&[^\p{Lu}]] </tt></td> 228 * <td headers="matches">Any letter except an uppercase letter (subtraction)</td></tr> 229 * 230 * <tr><th> </th></tr> 231 * <tr align="left"><th colspan="2" id="bounds">Boundary matchers</th></tr> 232 * 233 * <tr><td valign="top" headers="construct bounds"><tt>^</tt></td> 234 * <td headers="matches">The beginning of a line</td></tr> 235 * <tr><td valign="top" headers="construct bounds"><tt>$</tt></td> 236 * <td headers="matches">The end of a line</td></tr> 237 * <tr><td valign="top" headers="construct bounds"><tt>\b</tt></td> 238 * <td headers="matches">A word boundary</td></tr> 239 * <tr><td valign="top" headers="construct bounds"><tt>\B</tt></td> 240 * <td headers="matches">A non-word boundary</td></tr> 241 * <tr><td valign="top" headers="construct bounds"><tt>\A</tt></td> 242 * <td headers="matches">The beginning of the input</td></tr> 243 * <tr><td valign="top" headers="construct bounds"><tt>\G</tt></td> 244 * <td headers="matches">The end of the previous match</td></tr> 245 * <tr><td valign="top" headers="construct bounds"><tt>\Z</tt></td> 246 * <td headers="matches">The end of the input but for the final 247 * <a href="#lt">terminator</a>, if any</td></tr> 248 * <tr><td valign="top" headers="construct bounds"><tt>\z</tt></td> 249 * <td headers="matches">The end of the input</td></tr> 250 * 251 * <tr><th> </th></tr> 252 * <tr align="left"><th colspan="2" id="greedy">Greedy quantifiers</th></tr> 253 * 254 * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>?</tt></td> 255 * <td headers="matches"><i>X</i>, once or not at all</td></tr> 256 * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>*</tt></td> 257 * <td headers="matches"><i>X</i>, zero or more times</td></tr> 258 * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>+</tt></td> 259 * <td headers="matches"><i>X</i>, one or more times</td></tr> 260 * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>{</tt><i>n</i><tt>}</tt></td> 261 * <td headers="matches"><i>X</i>, exactly <i>n</i> times</td></tr> 262 * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>{</tt><i>n</i><tt>,}</tt></td> 263 * <td headers="matches"><i>X</i>, at least <i>n</i> times</td></tr> 264 * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>{</tt><i>n</i><tt>,</tt><i>m</i><tt>}</tt></td> 265 * <td headers="matches"><i>X</i>, at least <i>n</i> but not more than <i>m</i> times</td></tr> 266 * 267 * <tr><th> </th></tr> 268 * <tr align="left"><th colspan="2" id="reluc">Reluctant quantifiers</th></tr> 269 * 270 * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>??</tt></td> 271 * <td headers="matches"><i>X</i>, once or not at all</td></tr> 272 * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>*?</tt></td> 273 * <td headers="matches"><i>X</i>, zero or more times</td></tr> 274 * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>+?</tt></td> 275 * <td headers="matches"><i>X</i>, one or more times</td></tr> 276 * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>{</tt><i>n</i><tt>}?</tt></td> 277 * <td headers="matches"><i>X</i>, exactly <i>n</i> times</td></tr> 278 * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>{</tt><i>n</i><tt>,}?</tt></td> 279 * <td headers="matches"><i>X</i>, at least <i>n</i> times</td></tr> 280 * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>{</tt><i>n</i><tt>,</tt><i>m</i><tt>}?</tt></td> 281 * <td headers="matches"><i>X</i>, at least <i>n</i> but not more than <i>m</i> times</td></tr> 282 * 283 * <tr><th> </th></tr> 284 * <tr align="left"><th colspan="2" id="poss">Possessive quantifiers</th></tr> 285 * 286 * <tr><td valign="top" headers="construct poss"><i>X</i><tt>?+</tt></td> 287 * <td headers="matches"><i>X</i>, once or not at all</td></tr> 288 * <tr><td valign="top" headers="construct poss"><i>X</i><tt>*+</tt></td> 289 * <td headers="matches"><i>X</i>, zero or more times</td></tr> 290 * <tr><td valign="top" headers="construct poss"><i>X</i><tt>++</tt></td> 291 * <td headers="matches"><i>X</i>, one or more times</td></tr> 292 * <tr><td valign="top" headers="construct poss"><i>X</i><tt>{</tt><i>n</i><tt>}+</tt></td> 293 * <td headers="matches"><i>X</i>, exactly <i>n</i> times</td></tr> 294 * <tr><td valign="top" headers="construct poss"><i>X</i><tt>{</tt><i>n</i><tt>,}+</tt></td> 295 * <td headers="matches"><i>X</i>, at least <i>n</i> times</td></tr> 296 * <tr><td valign="top" headers="construct poss"><i>X</i><tt>{</tt><i>n</i><tt>,</tt><i>m</i><tt>}+</tt></td> 297 * <td headers="matches"><i>X</i>, at least <i>n</i> but not more than <i>m</i> times</td></tr> 298 * 299 * <tr><th> </th></tr> 300 * <tr align="left"><th colspan="2" id="logical">Logical operators</th></tr> 301 * 302 * <tr><td valign="top" headers="construct logical"><i>XY</i></td> 303 * <td headers="matches"><i>X</i> followed by <i>Y</i></td></tr> 304 * <tr><td valign="top" headers="construct logical"><i>X</i><tt>|</tt><i>Y</i></td> 305 * <td headers="matches">Either <i>X</i> or <i>Y</i></td></tr> 306 * <tr><td valign="top" headers="construct logical"><tt>(</tt><i>X</i><tt>)</tt></td> 307 * <td headers="matches">X, as a <a href="#cg">capturing group</a></td></tr> 308 * 309 * <tr><th> </th></tr> 310 * <tr align="left"><th colspan="2" id="backref">Back references</th></tr> 311 * 312 * <tr><td valign="bottom" headers="construct backref"><tt>\</tt><i>n</i></td> 313 * <td valign="bottom" headers="matches">Whatever the <i>n</i><sup>th</sup> 314 * <a href="#cg">capturing group</a> matched</td></tr> 315 * 316 * <tr><td valign="bottom" headers="construct backref"><tt>\</tt><i>k</i><<i>name</i>></td> 317 * <td valign="bottom" headers="matches">Whatever the 318 * <a href="#groupname">named-capturing group</a> "name" matched. Only available for API 26 or above</td></tr> 319 * 320 * <tr><th> </th></tr> 321 * <tr align="left"><th colspan="2" id="quot">Quotation</th></tr> 322 * 323 * <tr><td valign="top" headers="construct quot"><tt>\</tt></td> 324 * <td headers="matches">Nothing, but quotes the following character</td></tr> 325 * <tr><td valign="top" headers="construct quot"><tt>\Q</tt></td> 326 * <td headers="matches">Nothing, but quotes all characters until <tt>\E</tt></td></tr> 327 * <tr><td valign="top" headers="construct quot"><tt>\E</tt></td> 328 * <td headers="matches">Nothing, but ends quoting started by <tt>\Q</tt></td></tr> 329 * <!-- Metachars: !$()*+.<>?[\]^{|} --> 330 * 331 * <tr><th> </th></tr> 332 * <tr align="left"><th colspan="2" id="special">Special constructs (named-capturing and non-capturing)</th></tr> 333 * 334 * <tr><td valign="top" headers="construct special"><tt>(?<<a href="#groupname">name</a>></tt><i>X</i><tt>)</tt></td> 335 * <td headers="matches"><i>X</i>, as a named-capturing group. Only available for API 26 or above.</td></tr> 336 * <tr><td valign="top" headers="construct special"><tt>(?:</tt><i>X</i><tt>)</tt></td> 337 * <td headers="matches"><i>X</i>, as a non-capturing group</td></tr> 338 * <tr><td valign="top" headers="construct special"><tt>(?idmsuxU-idmsuxU) </tt></td> 339 * <td headers="matches">Nothing, but turns match flags <a href="#CASE_INSENSITIVE">i</a> 340 * <a href="#UNIX_LINES">d</a> <a href="#MULTILINE">m</a> <a href="#DOTALL">s</a> 341 * <a href="#UNICODE_CASE">u</a> <a href="#COMMENTS">x</a> <a href="#UNICODE_CHARACTER_CLASS">U</a> 342 * on - off</td></tr> 343 * <tr><td valign="top" headers="construct special"><tt>(?idmsux-idmsux:</tt><i>X</i><tt>)</tt> </td> 344 * <td headers="matches"><i>X</i>, as a <a href="#cg">non-capturing group</a> with the 345 * given flags <a href="#CASE_INSENSITIVE">i</a> <a href="#UNIX_LINES">d</a> 346 * <a href="#MULTILINE">m</a> <a href="#DOTALL">s</a> <a href="#UNICODE_CASE">u</a > 347 * <a href="#COMMENTS">x</a> on - off</td></tr> 348 * <tr><td valign="top" headers="construct special"><tt>(?=</tt><i>X</i><tt>)</tt></td> 349 * <td headers="matches"><i>X</i>, via zero-width positive lookahead</td></tr> 350 * <tr><td valign="top" headers="construct special"><tt>(?!</tt><i>X</i><tt>)</tt></td> 351 * <td headers="matches"><i>X</i>, via zero-width negative lookahead</td></tr> 352 * <tr><td valign="top" headers="construct special"><tt>(?<=</tt><i>X</i><tt>)</tt></td> 353 * <td headers="matches"><i>X</i>, via zero-width positive lookbehind</td></tr> 354 * <tr><td valign="top" headers="construct special"><tt>(?<!</tt><i>X</i><tt>)</tt></td> 355 * <td headers="matches"><i>X</i>, via zero-width negative lookbehind</td></tr> 356 * <tr><td valign="top" headers="construct special"><tt>(?></tt><i>X</i><tt>)</tt></td> 357 * <td headers="matches"><i>X</i>, as an independent, non-capturing group</td></tr> 358 * 359 * </table> 360 * 361 * <hr> 362 * 363 * 364 * <a name="bs"> 365 * <h4> Backslashes, escapes, and quoting </h4> 366 * 367 * <p> The backslash character (<tt>'\'</tt>) serves to introduce escaped 368 * constructs, as defined in the table above, as well as to quote characters 369 * that otherwise would be interpreted as unescaped constructs. Thus the 370 * expression <tt>\\</tt> matches a single backslash and <tt>\{</tt> matches a 371 * left brace. 372 * 373 * <p> It is an error to use a backslash prior to any alphabetic character that 374 * does not denote an escaped construct; these are reserved for future 375 * extensions to the regular-expression language. A backslash may be used 376 * prior to a non-alphabetic character regardless of whether that character is 377 * part of an unescaped construct. 378 * 379 * <p> Backslashes within string literals in Java source code are interpreted 380 * as required by 381 * <cite>The Java™ Language Specification</cite> 382 * as either Unicode escapes (section 3.3) or other character escapes (section 3.10.6) 383 * It is therefore necessary to double backslashes in string 384 * literals that represent regular expressions to protect them from 385 * interpretation by the Java bytecode compiler. The string literal 386 * <tt>"\b"</tt>, for example, matches a single backspace character when 387 * interpreted as a regular expression, while <tt>"\\b"</tt> matches a 388 * word boundary. The string literal <tt>"\(hello\)"</tt> is illegal 389 * and leads to a compile-time error; in order to match the string 390 * <tt>(hello)</tt> the string literal <tt>"\\(hello\\)"</tt> 391 * must be used. 392 * 393 * <a name="cc"> 394 * <h4> Character Classes </h4> 395 * 396 * <p> Character classes may appear within other character classes, and 397 * may be composed by the union operator (implicit) and the intersection 398 * operator (<tt>&&</tt>). 399 * The union operator denotes a class that contains every character that is 400 * in at least one of its operand classes. The intersection operator 401 * denotes a class that contains every character that is in both of its 402 * operand classes. 403 * 404 * <p> The precedence of character-class operators is as follows, from 405 * highest to lowest: 406 * 407 * <blockquote><table border="0" cellpadding="1" cellspacing="0" 408 * summary="Precedence of character class operators."> 409 * <tr><th>1 </th> 410 * <td>Literal escape </td> 411 * <td><tt>\x</tt></td></tr> 412 * <tr><th>2 </th> 413 * <td>Grouping</td> 414 * <td><tt>[...]</tt></td></tr> 415 * <tr><th>3 </th> 416 * <td>Range</td> 417 * <td><tt>a-z</tt></td></tr> 418 * <tr><th>4 </th> 419 * <td>Union</td> 420 * <td><tt>[a-e][i-u]</tt></td></tr> 421 * <tr><th>5 </th> 422 * <td>Intersection</td> 423 * <td><tt>[a-z&&[aeiou]]</tt></td></tr> 424 * </table></blockquote> 425 * 426 * <p> Note that a different set of metacharacters are in effect inside 427 * a character class than outside a character class. For instance, the 428 * regular expression <tt>.</tt> loses its special meaning inside a 429 * character class, while the expression <tt>-</tt> becomes a range 430 * forming metacharacter. 431 * 432 * <a name="lt"> 433 * <h4> Line terminators </h4> 434 * 435 * <p> A <i>line terminator</i> is a one- or two-character sequence that marks 436 * the end of a line of the input character sequence. The following are 437 * recognized as line terminators: 438 * 439 * <ul> 440 * 441 * <li> A newline (line feed) character (<tt>'\n'</tt>), 442 * 443 * <li> A carriage-return character followed immediately by a newline 444 * character (<tt>"\r\n"</tt>), 445 * 446 * <li> A standalone carriage-return character (<tt>'\r'</tt>), 447 * 448 * <li> A next-line character (<tt>'\u0085'</tt>), 449 * 450 * <li> A line-separator character (<tt>'\u2028'</tt>), or 451 * 452 * <li> A paragraph-separator character (<tt>'\u2029</tt>). 453 * 454 * </ul> 455 * <p>If {@link #UNIX_LINES} mode is activated, then the only line terminators 456 * recognized are newline characters. 457 * 458 * <p> The regular expression <tt>.</tt> matches any character except a line 459 * terminator unless the {@link #DOTALL} flag is specified. 460 * 461 * <p> By default, the regular expressions <tt>^</tt> and <tt>$</tt> ignore 462 * line terminators and only match at the beginning and the end, respectively, 463 * of the entire input sequence. If {@link #MULTILINE} mode is activated then 464 * <tt>^</tt> matches at the beginning of input and after any line terminator 465 * except at the end of input. When in {@link #MULTILINE} mode <tt>$</tt> 466 * matches just before a line terminator or the end of the input sequence. 467 * 468 * <a name="cg"> 469 * <h4> Groups and capturing </h4> 470 * 471 * <a name="gnumber"> 472 * <h5> Group number </h5> 473 * <p> Capturing groups are numbered by counting their opening parentheses from 474 * left to right. In the expression <tt>((A)(B(C)))</tt>, for example, there 475 * are four such groups: </p> 476 * 477 * <blockquote><table cellpadding=1 cellspacing=0 summary="Capturing group numberings"> 478 * <tr><th>1 </th> 479 * <td><tt>((A)(B(C)))</tt></td></tr> 480 * <tr><th>2 </th> 481 * <td><tt>(A)</tt></td></tr> 482 * <tr><th>3 </th> 483 * <td><tt>(B(C))</tt></td></tr> 484 * <tr><th>4 </th> 485 * <td><tt>(C)</tt></td></tr> 486 * </table></blockquote> 487 * 488 * <p> Group zero always stands for the entire expression. 489 * 490 * <p> Capturing groups are so named because, during a match, each subsequence 491 * of the input sequence that matches such a group is saved. The captured 492 * subsequence may be used later in the expression, via a back reference, and 493 * may also be retrieved from the matcher once the match operation is complete. 494 * 495 * <a name="groupname"> 496 * <h5> Group name </h5> 497 * <p>The constructs and APIs are available since API level 26. A capturing group 498 * can also be assigned a "name", a <tt>named-capturing group</tt>, 499 * and then be back-referenced later by the "name". Group names are composed of 500 * the following characters. The first character must be a <tt>letter</tt>. 501 * 502 * <ul> 503 * <li> The uppercase letters <tt>'A'</tt> through <tt>'Z'</tt> 504 * (<tt>'\u0041'</tt> through <tt>'\u005a'</tt>), 505 * <li> The lowercase letters <tt>'a'</tt> through <tt>'z'</tt> 506 * (<tt>'\u0061'</tt> through <tt>'\u007a'</tt>), 507 * <li> The digits <tt>'0'</tt> through <tt>'9'</tt> 508 * (<tt>'\u0030'</tt> through <tt>'\u0039'</tt>), 509 * </ul> 510 * 511 * <p> A <tt>named-capturing group</tt> is still numbered as described in 512 * <a href="#gnumber">Group number</a>. 513 * 514 * <p> The captured input associated with a group is always the subsequence 515 * that the group most recently matched. If a group is evaluated a second time 516 * because of quantification then its previously-captured value, if any, will 517 * be retained if the second evaluation fails. Matching the string 518 * <tt>"aba"</tt> against the expression <tt>(a(b)?)+</tt>, for example, leaves 519 * group two set to <tt>"b"</tt>. All captured input is discarded at the 520 * beginning of each match. 521 * 522 * <p> Groups beginning with <tt>(?</tt> are either pure, <i>non-capturing</i> groups 523 * that do not capture text and do not count towards the group total, or 524 * <i>named-capturing</i> group. 525 * 526 * <h4> Unicode support </h4> 527 * 528 * <p> This class is in conformance with Level 1 of <a 529 * href="http://www.unicode.org/reports/tr18/"><i>Unicode Technical 530 * Standard #18: Unicode Regular Expression</i></a>, plus RL2.1 531 * Canonical Equivalents. 532 * <p> 533 * <b>Unicode escape sequences</b> such as <tt>\u2014</tt> in Java source code 534 * are processed as described in section 3.3 of 535 * <cite>The Java™ Language Specification</cite>. 536 * Such escape sequences are also implemented directly by the regular-expression 537 * parser so that Unicode escapes can be used in expressions that are read from 538 * files or from the keyboard. Thus the strings <tt>"\u2014"</tt> and 539 * <tt>"\\u2014"</tt>, while not equal, compile into the same pattern, which 540 * matches the character with hexadecimal value <tt>0x2014</tt>. 541 * <p> 542 * A Unicode character can also be represented in a regular-expression by 543 * using its <b>Hex notation</b>(hexadecimal code point value) directly as described in construct 544 * <tt>\x{...}</tt>, for example a supplementary character U+2011F 545 * can be specified as <tt>\x{2011F}</tt>, instead of two consecutive 546 * Unicode escape sequences of the surrogate pair 547 * <tt>\uD840</tt><tt>\uDD1F</tt>. 548 * <p> 549 * Unicode scripts, blocks, categories and binary properties are written with 550 * the <tt>\p</tt> and <tt>\P</tt> constructs as in Perl. 551 * <tt>\p{</tt><i>prop</i><tt>}</tt> matches if 552 * the input has the property <i>prop</i>, while <tt>\P{</tt><i>prop</i><tt>}</tt> 553 * does not match if the input has that property. 554 * <p> 555 * Scripts, blocks, categories and binary properties can be used both inside 556 * and outside of a character class. 557 * <a name="usc"> 558 * <p> 559 * <b>Scripts</b> are specified either with the prefix {@code Is}, as in 560 * {@code IsHiragana}, or by using the {@code script} keyword (or its short 561 * form {@code sc})as in {@code script=Hiragana} or {@code sc=Hiragana}. 562 * <p> 563 * The script names supported by <code>Pattern</code> are the valid script names 564 * accepted and defined by 565 * {@link java.lang.Character.UnicodeScript#forName(String) UnicodeScript.forName}. 566 * <a name="ubc"> 567 * <p> 568 * <b>Blocks</b> are specified with the prefix {@code In}, as in 569 * {@code InMongolian}, or by using the keyword {@code block} (or its short 570 * form {@code blk}) as in {@code block=Mongolian} or {@code blk=Mongolian}. 571 * <p> 572 * The block names supported by <code>Pattern</code> are the valid block names 573 * accepted and defined by 574 * {@link java.lang.Character.UnicodeBlock#forName(String) UnicodeBlock.forName}. 575 * <p> 576 * <a name="ucc"> 577 * <b>Categories</b> may be specified with the optional prefix {@code Is}: 578 * Both {@code \p{L}} and {@code \p{IsL}} denote the category of Unicode 579 * letters. Same as scripts and blocks, categories can also be specified 580 * by using the keyword {@code general_category} (or its short form 581 * {@code gc}) as in {@code general_category=Lu} or {@code gc=Lu}. 582 * <p> 583 * The supported categories are those of 584 * <a href="http://www.unicode.org/unicode/standard/standard.html"> 585 * <i>The Unicode Standard</i></a> in the version specified by the 586 * {@link java.lang.Character Character} class. The category names are those 587 * defined in the Standard, both normative and informative. 588 * <p> 589 * <a name="ubpc"> 590 * <b>Binary properties</b> are specified with the prefix {@code Is}, as in 591 * {@code IsAlphabetic}. The supported binary properties by <code>Pattern</code> 592 * are 593 * <ul> 594 * <li> Alphabetic 595 * <li> Ideographic 596 * <li> Letter 597 * <li> Lowercase 598 * <li> Uppercase 599 * <li> Titlecase 600 * <li> Punctuation 601 * <Li> Control 602 * <li> White_Space 603 * <li> Digit 604 * <li> Hex_Digit 605 * <li> Noncharacter_Code_Point 606 * <li> Assigned 607 * </ul> 608 609 610 * <p> 611 * <b>Predefined Character classes</b> and <b>POSIX character classes</b> are in 612 * conformance with the recommendation of <i>Annex C: Compatibility Properties</i> 613 * of <a href="http://www.unicode.org/reports/tr18/"><i>Unicode Regular Expression 614 * </i></a>. 615 * <p> 616 * <table border="0" cellpadding="1" cellspacing="0" 617 * summary="predefined and posix character classes in Unicode mode"> 618 * <tr align="left"> 619 * <th bgcolor="#CCCCFF" align="left" id="classes">Classes</th> 620 * <th bgcolor="#CCCCFF" align="left" id="matches">Matches</th> 621 *</tr> 622 * <tr><td><tt>\p{Lower}</tt></td> 623 * <td>A lowercase character:<tt>\p{IsLowercase}</tt></td></tr> 624 * <tr><td><tt>\p{Upper}</tt></td> 625 * <td>An uppercase character:<tt>\p{IsUppercase}</tt></td></tr> 626 * <tr><td><tt>\p{ASCII}</tt></td> 627 * <td>All ASCII:<tt>[\x00-\x7F]</tt></td></tr> 628 * <tr><td><tt>\p{Alpha}</tt></td> 629 * <td>An alphabetic character:<tt>\p{IsAlphabetic}</tt></td></tr> 630 * <tr><td><tt>\p{Digit}</tt></td> 631 * <td>A decimal digit character:<tt>p{IsDigit}</tt></td></tr> 632 * <tr><td><tt>\p{Alnum}</tt></td> 633 * <td>An alphanumeric character:<tt>[\p{IsAlphabetic}\p{IsDigit}]</tt></td></tr> 634 * <tr><td><tt>\p{Punct}</tt></td> 635 * <td>A punctuation character:<tt>p{IsPunctuation}</tt></td></tr> 636 * <tr><td><tt>\p{Graph}</tt></td> 637 * <td>A visible character: <tt>[^\p{IsWhite_Space}\p{gc=Cc}\p{gc=Cs}\p{gc=Cn}]</tt></td></tr> 638 * <tr><td><tt>\p{Print}</tt></td> 639 * <td>A printable character: <tt>[\p{Graph}\p{Blank}&&[^\p{Cntrl}]]</tt></td></tr> 640 * <tr><td><tt>\p{Blank}</tt></td> 641 * <td>A space or a tab: <tt>[\p{IsWhite_Space}&&[^\p{gc=Zl}\p{gc=Zp}\x0a\x0b\x0c\x0d\x85]]</tt></td></tr> 642 * <tr><td><tt>\p{Cntrl}</tt></td> 643 * <td>A control character: <tt>\p{gc=Cc}</tt></td></tr> 644 * <tr><td><tt>\p{XDigit}</tt></td> 645 * <td>A hexadecimal digit: <tt>[\p{gc=Nd}\p{IsHex_Digit}]</tt></td></tr> 646 * <tr><td><tt>\p{Space}</tt></td> 647 * <td>A whitespace character:<tt>\p{IsWhite_Space}</tt></td></tr> 648 * <tr><td><tt>\d</tt></td> 649 * <td>A digit: <tt>\p{IsDigit}</tt></td></tr> 650 * <tr><td><tt>\D</tt></td> 651 * <td>A non-digit: <tt>[^\d]</tt></td></tr> 652 * <tr><td><tt>\s</tt></td> 653 * <td>A whitespace character: <tt>\p{IsWhite_Space}</tt></td></tr> 654 * <tr><td><tt>\S</tt></td> 655 * <td>A non-whitespace character: <tt>[^\s]</tt></td></tr> 656 * <tr><td><tt>\w</tt></td> 657 * <td>A word character: <tt>[\p{Alpha}\p{gc=Mn}\p{gc=Me}\p{gc=Mc}\p{Digit}\p{gc=Pc}]</tt></td></tr> 658 * <tr><td><tt>\W</tt></td> 659 * <td>A non-word character: <tt>[^\w]</tt></td></tr> 660 * </table> 661 * <p> 662 * <a name="jcc"> 663 * Categories that behave like the java.lang.Character 664 * boolean is<i>methodname</i> methods (except for the deprecated ones) are 665 * available through the same <tt>\p{</tt><i>prop</i><tt>}</tt> syntax where 666 * the specified property has the name <tt>java<i>methodname</i></tt>. 667 * 668 * <h4> Comparison to Perl 5 </h4> 669 * 670 * <p>The <code>Pattern</code> engine performs traditional NFA-based matching 671 * with ordered alternation as occurs in Perl 5. 672 * 673 * <p> Perl constructs not supported by this class: </p> 674 * 675 * <ul> 676 * <li><p> Predefined character classes (Unicode character) 677 * <p><tt>\h </tt>A horizontal whitespace 678 * <p><tt>\H </tt>A non horizontal whitespace 679 * <p><tt>\v </tt>A vertical whitespace 680 * <p><tt>\V </tt>A non vertical whitespace 681 * <p><tt>\R </tt>Any Unicode linebreak sequence 682 * <tt>\u005cu000D\u005cu000A|[\u005cu000A\u005cu000B\u005cu000C\u005cu000D\u005cu0085\u005cu2028\u005cu2029]</tt> 683 * <p><tt>\X </tt>Match Unicode 684 * <a href="http://www.unicode.org/reports/tr18/#Default_Grapheme_Clusters"> 685 * <i>extended grapheme cluster</i></a> 686 * </p></li> 687 * 688 * <li><p> The backreference constructs, <tt>\g{</tt><i>n</i><tt>}</tt> for 689 * the <i>n</i><sup>th</sup><a href="#cg">capturing group</a> and 690 * <tt>\g{</tt><i>name</i><tt>}</tt> for 691 * <a href="#groupname">named-capturing group</a>. 692 * </p></li> 693 * 694 * <li><p> The named character construct, <tt>\N{</tt><i>name</i><tt>}</tt> 695 * for a Unicode character by its name. 696 * </p></li> 697 * 698 * <li><p> The conditional constructs 699 * <tt>(?(</tt><i>condition</i><tt>)</tt><i>X</i><tt>)</tt> and 700 * <tt>(?(</tt><i>condition</i><tt>)</tt><i>X</i><tt>|</tt><i>Y</i><tt>)</tt>, 701 * </p></li> 702 * 703 * <li><p> The embedded code constructs <tt>(?{</tt><i>code</i><tt>})</tt> 704 * and <tt>(??{</tt><i>code</i><tt>})</tt>,</p></li> 705 * 706 * <li><p> The embedded comment syntax <tt>(?#comment)</tt>, and </p></li> 707 * 708 * <li><p> The preprocessing operations <tt>\l</tt> <tt>\u</tt>, 709 * <tt>\L</tt>, and <tt>\U</tt>. </p></li> 710 * 711 * </ul> 712 * 713 * <p> Constructs supported by this class but not by Perl: </p> 714 * 715 * <ul> 716 * 717 * <li><p> Character-class union and intersection as described 718 * <a href="#cc">above</a>.</p></li> 719 * 720 * </ul> 721 * 722 * <p> Notable differences from Perl: </p> 723 * 724 * <ul> 725 * 726 * <li><p> In Perl, <tt>\1</tt> through <tt>\9</tt> are always interpreted 727 * as back references; a backslash-escaped number greater than <tt>9</tt> is 728 * treated as a back reference if at least that many subexpressions exist, 729 * otherwise it is interpreted, if possible, as an octal escape. In this 730 * class octal escapes must always begin with a zero. In this class, 731 * <tt>\1</tt> through <tt>\9</tt> are always interpreted as back 732 * references, and a larger number is accepted as a back reference if at 733 * least that many subexpressions exist at that point in the regular 734 * expression, otherwise the parser will drop digits until the number is 735 * smaller or equal to the existing number of groups or it is one digit. 736 * </p></li> 737 * 738 * <li><p> Perl uses the <tt>g</tt> flag to request a match that resumes 739 * where the last match left off. This functionality is provided implicitly 740 * by the {@link Matcher} class: Repeated invocations of the {@link 741 * Matcher#find find} method will resume where the last match left off, 742 * unless the matcher is reset. </p></li> 743 * 744 * <li><p> In Perl, embedded flags at the top level of an expression affect 745 * the whole expression. In this class, embedded flags always take effect 746 * at the point at which they appear, whether they are at the top level or 747 * within a group; in the latter case, flags are restored at the end of the 748 * group just as in Perl. </p></li> 749 * 750 * </ul> 751 * 752 * 753 * <p> For a more precise description of the behavior of regular expression 754 * constructs, please see <a href="http://www.oreilly.com/catalog/regex3/"> 755 * <i>Mastering Regular Expressions, 3nd Edition</i>, Jeffrey E. F. Friedl, 756 * O'Reilly and Associates, 2006.</a> 757 * </p> 758 * 759 * @see java.lang.String#split(String, int) 760 * @see java.lang.String#split(String) 761 * 762 * @author Mike McCloskey 763 * @author Mark Reinhold 764 * @author JSR-51 Expert Group 765 * @since 1.4 766 * @spec JSR-51 767 */ 768 769public final class Pattern implements java.io.Serializable 770{ 771 772 /** 773 * Regular expression modifier values. Instead of being passed as 774 * arguments, they can also be passed as inline modifiers. 775 * For example, the following statements have the same effect. 776 * <pre> 777 * RegExp r1 = RegExp.compile("abc", Pattern.I|Pattern.M); 778 * RegExp r2 = RegExp.compile("(?im)abc", 0); 779 * </pre> 780 * 781 * The flags are duplicated so that the familiar Perl match flag 782 * names are available. 783 */ 784 785 /** 786 * Enables Unix lines mode. 787 * 788 * <p> In this mode, only the <tt>'\n'</tt> line terminator is recognized 789 * in the behavior of <tt>.</tt>, <tt>^</tt>, and <tt>$</tt>. 790 * 791 * <p> Unix lines mode can also be enabled via the embedded flag 792 * expression <tt>(?d)</tt>. 793 */ 794 public static final int UNIX_LINES = 0x01; 795 796 /** 797 * Enables case-insensitive matching. 798 * 799 * <p> By default, case-insensitive matching assumes that only characters 800 * in the US-ASCII charset are being matched. Unicode-aware 801 * case-insensitive matching can be enabled by specifying the {@link 802 * #UNICODE_CASE} flag in conjunction with this flag. 803 * 804 * <p> Case-insensitive matching can also be enabled via the embedded flag 805 * expression <tt>(?i)</tt>. 806 * 807 * <p> Specifying this flag may impose a slight performance penalty. </p> 808 */ 809 public static final int CASE_INSENSITIVE = 0x02; 810 811 /** 812 * Permits whitespace and comments in pattern. 813 * 814 * <p> In this mode, whitespace is ignored, and embedded comments starting 815 * with <tt>#</tt> are ignored until the end of a line. 816 * 817 * <p> Comments mode can also be enabled via the embedded flag 818 * expression <tt>(?x)</tt>. 819 */ 820 public static final int COMMENTS = 0x04; 821 822 /** 823 * Enables multiline mode. 824 * 825 * <p> In multiline mode the expressions <tt>^</tt> and <tt>$</tt> match 826 * just after or just before, respectively, a line terminator or the end of 827 * the input sequence. By default these expressions only match at the 828 * beginning and the end of the entire input sequence. 829 * 830 * <p> Multiline mode can also be enabled via the embedded flag 831 * expression <tt>(?m)</tt>. </p> 832 */ 833 public static final int MULTILINE = 0x08; 834 835 /** 836 * Enables literal parsing of the pattern. 837 * 838 * <p> When this flag is specified then the input string that specifies 839 * the pattern is treated as a sequence of literal characters. 840 * Metacharacters or escape sequences in the input sequence will be 841 * given no special meaning. 842 * 843 * <p>The flags CASE_INSENSITIVE and UNICODE_CASE retain their impact on 844 * matching when used in conjunction with this flag. The other flags 845 * become superfluous. 846 * 847 * <p> There is no embedded flag character for enabling literal parsing. 848 * @since 1.5 849 */ 850 public static final int LITERAL = 0x10; 851 852 /** 853 * Enables dotall mode. 854 * 855 * <p> In dotall mode, the expression <tt>.</tt> matches any character, 856 * including a line terminator. By default this expression does not match 857 * line terminators. 858 * 859 * <p> Dotall mode can also be enabled via the embedded flag 860 * expression <tt>(?s)</tt>. (The <tt>s</tt> is a mnemonic for 861 * "single-line" mode, which is what this is called in Perl.) </p> 862 */ 863 public static final int DOTALL = 0x20; 864 865 /** 866 * Enables Unicode-aware case folding. 867 * 868 * <p> When this flag is specified then case-insensitive matching, when 869 * enabled by the {@link #CASE_INSENSITIVE} flag, is done in a manner 870 * consistent with the Unicode Standard. By default, case-insensitive 871 * matching assumes that only characters in the US-ASCII charset are being 872 * matched. 873 * 874 * <p> Unicode-aware case folding can also be enabled via the embedded flag 875 * expression <tt>(?u)</tt>. 876 * 877 * <p> Specifying this flag may impose a performance penalty. </p> 878 */ 879 public static final int UNICODE_CASE = 0x40; 880 881 /** 882 * Enables canonical equivalence. 883 * 884 * <p> When this flag is specified then two characters will be considered 885 * to match if, and only if, their full canonical decompositions match. 886 * The expression <tt>"a\u030A"</tt>, for example, will match the 887 * string <tt>"\u00E5"</tt> when this flag is specified. By default, 888 * matching does not take canonical equivalence into account. 889 * 890 * <p> There is no embedded flag character for enabling canonical 891 * equivalence. 892 * 893 * <p> Specifying this flag may impose a performance penalty. </p> 894 */ 895 public static final int CANON_EQ = 0x80; 896 897 /** 898 * Enables the Unicode version of <i>Predefined character classes</i> and 899 * <i>POSIX character classes</i> as eefined by <a href="http://www.unicode.org/reports/tr18/"><i>Unicode Technical 900 * Standard #18: Unicode Regular Expression</i></a> 901 * <i>Annex C: Compatibility Properties</i>. 902 * <p> 903 * 904 * This flag has no effect on Android, unicode character classes are always 905 * used. 906 * 907 * @since 1.7 908 */ 909 public static final int UNICODE_CHARACTER_CLASS = 0x100; 910 911 /* Pattern has only two serialized components: The pattern string 912 * and the flags, which are all that is needed to recompile the pattern 913 * when it is deserialized. 914 */ 915 916 /** use serialVersionUID from Merlin b59 for interoperability */ 917 private static final long serialVersionUID = 5073258162644648461L; 918 919 /** 920 * The original regular-expression pattern string. 921 * 922 * @serial 923 */ 924 private final String pattern; 925 926 /** 927 * The original pattern flags. 928 * 929 * @serial 930 */ 931 private final int flags; 932 933 @ReachabilitySensitive 934 transient long address; 935 936 private static final NativeAllocationRegistry registry = new NativeAllocationRegistry( 937 Pattern.class.getClassLoader(), getNativeFinalizer(), nativeSize()); 938 939 940 /** 941 * Compiles the given regular expression into a pattern. </p> 942 * 943 * @param regex 944 * The expression to be compiled 945 * 946 * @throws PatternSyntaxException 947 * If the expression's syntax is invalid 948 */ 949 public static Pattern compile(String regex) { 950 return new Pattern(regex, 0); 951 } 952 953 /** 954 * Compiles the given regular expression into a pattern with the given 955 * flags. </p> 956 * 957 * @param regex 958 * The expression to be compiled 959 * 960 * @param flags 961 * Match flags, a bit mask that may include 962 * {@link #CASE_INSENSITIVE}, {@link #MULTILINE}, {@link #DOTALL}, 963 * {@link #UNICODE_CASE}, {@link #CANON_EQ}, {@link #UNIX_LINES}, 964 * {@link #LITERAL}, {@link #UNICODE_CHARACTER_CLASS} 965 * and {@link #COMMENTS} 966 * 967 * @throws IllegalArgumentException 968 * If bit values other than those corresponding to the defined 969 * match flags are set in <tt>flags</tt> 970 * 971 * @throws PatternSyntaxException 972 * If the expression's syntax is invalid 973 */ 974 public static Pattern compile(String regex, int flags) throws PatternSyntaxException { 975 return new Pattern(regex, flags); 976 } 977 978 /** 979 * Returns the regular expression from which this pattern was compiled. 980 * </p> 981 * 982 * @return The source of this pattern 983 */ 984 public String pattern() { 985 return pattern; 986 } 987 988 /** 989 * <p>Returns the string representation of this pattern. This 990 * is the regular expression from which this pattern was 991 * compiled.</p> 992 * 993 * @return The string representation of this pattern 994 * @since 1.5 995 */ 996 public String toString() { 997 return pattern; 998 } 999 1000 /** 1001 * Creates a matcher that will match the given input against this pattern. 1002 * </p> 1003 * 1004 * @param input 1005 * The character sequence to be matched 1006 * 1007 * @return A new matcher for this pattern 1008 */ 1009 public Matcher matcher(CharSequence input) { 1010 Matcher m = new Matcher(this, input); 1011 return m; 1012 } 1013 1014 /** 1015 * Returns this pattern's match flags. </p> 1016 * 1017 * @return The match flags specified when this pattern was compiled 1018 */ 1019 public int flags() { 1020 return flags; 1021 } 1022 1023 /** 1024 * Compiles the given regular expression and attempts to match the given 1025 * input against it. 1026 * 1027 * <p> An invocation of this convenience method of the form 1028 * 1029 * <blockquote><pre> 1030 * Pattern.matches(regex, input);</pre></blockquote> 1031 * 1032 * behaves in exactly the same way as the expression 1033 * 1034 * <blockquote><pre> 1035 * Pattern.compile(regex).matcher(input).matches()</pre></blockquote> 1036 * 1037 * <p> If a pattern is to be used multiple times, compiling it once and reusing 1038 * it will be more efficient than invoking this method each time. </p> 1039 * 1040 * @param regex 1041 * The expression to be compiled 1042 * 1043 * @param input 1044 * The character sequence to be matched 1045 * 1046 * @throws PatternSyntaxException 1047 * If the expression's syntax is invalid 1048 */ 1049 public static boolean matches(String regex, CharSequence input) { 1050 Pattern p = Pattern.compile(regex); 1051 Matcher m = p.matcher(input); 1052 return m.matches(); 1053 } 1054 1055 /** 1056 * Splits the given input sequence around matches of this pattern. 1057 * 1058 * <p> The array returned by this method contains each substring of the 1059 * input sequence that is terminated by another subsequence that matches 1060 * this pattern or is terminated by the end of the input sequence. The 1061 * substrings in the array are in the order in which they occur in the 1062 * input. If this pattern does not match any subsequence of the input then 1063 * the resulting array has just one element, namely the input sequence in 1064 * string form. 1065 * 1066 * <p> The <tt>limit</tt> parameter controls the number of times the 1067 * pattern is applied and therefore affects the length of the resulting 1068 * array. If the limit <i>n</i> is greater than zero then the pattern 1069 * will be applied at most <i>n</i> - 1 times, the array's 1070 * length will be no greater than <i>n</i>, and the array's last entry 1071 * will contain all input beyond the last matched delimiter. If <i>n</i> 1072 * is non-positive then the pattern will be applied as many times as 1073 * possible and the array can have any length. If <i>n</i> is zero then 1074 * the pattern will be applied as many times as possible, the array can 1075 * have any length, and trailing empty strings will be discarded. 1076 * 1077 * <p> The input <tt>"boo:and:foo"</tt>, for example, yields the following 1078 * results with these parameters: 1079 * 1080 * <blockquote><table cellpadding=1 cellspacing=0 1081 * summary="Split examples showing regex, limit, and result"> 1082 * <tr><th><P align="left"><i>Regex </i></th> 1083 * <th><P align="left"><i>Limit </i></th> 1084 * <th><P align="left"><i>Result </i></th></tr> 1085 * <tr><td align=center>:</td> 1086 * <td align=center>2</td> 1087 * <td><tt>{ "boo", "and:foo" }</tt></td></tr> 1088 * <tr><td align=center>:</td> 1089 * <td align=center>5</td> 1090 * <td><tt>{ "boo", "and", "foo" }</tt></td></tr> 1091 * <tr><td align=center>:</td> 1092 * <td align=center>-2</td> 1093 * <td><tt>{ "boo", "and", "foo" }</tt></td></tr> 1094 * <tr><td align=center>o</td> 1095 * <td align=center>5</td> 1096 * <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr> 1097 * <tr><td align=center>o</td> 1098 * <td align=center>-2</td> 1099 * <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr> 1100 * <tr><td align=center>o</td> 1101 * <td align=center>0</td> 1102 * <td><tt>{ "b", "", ":and:f" }</tt></td></tr> 1103 * </table></blockquote> 1104 * 1105 * 1106 * @param input 1107 * The character sequence to be split 1108 * 1109 * @param limit 1110 * The result threshold, as described above 1111 * 1112 * @return The array of strings computed by splitting the input 1113 * around matches of this pattern 1114 */ 1115 public String[] split(CharSequence input, int limit) { 1116 String[] fast = fastSplit(pattern, input.toString(), limit); 1117 if (fast != null) { 1118 return fast; 1119 } 1120 1121 int index = 0; 1122 boolean matchLimited = limit > 0; 1123 ArrayList<String> matchList = new ArrayList<>(); 1124 Matcher m = matcher(input); 1125 1126 // Add segments before each match found 1127 while(m.find()) { 1128 if (!matchLimited || matchList.size() < limit - 1) { 1129 String match = input.subSequence(index, m.start()).toString(); 1130 matchList.add(match); 1131 index = m.end(); 1132 } else if (matchList.size() == limit - 1) { // last one 1133 String match = input.subSequence(index, 1134 input.length()).toString(); 1135 matchList.add(match); 1136 index = m.end(); 1137 } 1138 } 1139 1140 // If no match was found, return this 1141 if (index == 0) 1142 return new String[] {input.toString()}; 1143 1144 // Add remaining segment 1145 if (!matchLimited || matchList.size() < limit) 1146 matchList.add(input.subSequence(index, input.length()).toString()); 1147 1148 // Construct result 1149 int resultSize = matchList.size(); 1150 if (limit == 0) 1151 while (resultSize > 0 && matchList.get(resultSize-1).equals("")) 1152 resultSize--; 1153 String[] result = new String[resultSize]; 1154 return matchList.subList(0, resultSize).toArray(result); 1155 } 1156 1157 private static final String FASTSPLIT_METACHARACTERS = "\\?*+[](){}^$.|"; 1158 1159 /** 1160 * Returns a result equivalent to {@code s.split(separator, limit)} if it's able 1161 * to compute it more cheaply than native impl, or null if the caller should fall back to 1162 * using native impl. 1163 * 1164 * fastpath will work if the regex is a 1165 * (1)one-char String and this character is not one of the 1166 * RegEx's meta characters ".$|()[{^?*+\\", or 1167 * (2)two-char String and the first char is the backslash and 1168 * the second is one of regEx's meta characters ".$|()[{^?*+\\". 1169 * @hide 1170 */ 1171 public static String[] fastSplit(String re, String input, int limit) { 1172 // Can we do it cheaply? 1173 int len = re.length(); 1174 if (len == 0) { 1175 return null; 1176 } 1177 char ch = re.charAt(0); 1178 if (len == 1 && FASTSPLIT_METACHARACTERS.indexOf(ch) == -1) { 1179 // We're looking for a single non-metacharacter. Easy. 1180 } else if (len == 2 && ch == '\\') { 1181 // We're looking for a quoted character. 1182 // Quoted metacharacters are effectively single non-metacharacters. 1183 ch = re.charAt(1); 1184 if (FASTSPLIT_METACHARACTERS.indexOf(ch) == -1) { 1185 return null; 1186 } 1187 } else { 1188 return null; 1189 } 1190 1191 // We can do this cheaply... 1192 1193 // Unlike Perl, which considers the result of splitting the empty string to be the empty 1194 // array, Java returns an array containing the empty string. 1195 if (input.isEmpty()) { 1196 return new String[] { "" }; 1197 } 1198 1199 // Count separators 1200 int separatorCount = 0; 1201 int begin = 0; 1202 int end; 1203 while (separatorCount + 1 != limit && (end = input.indexOf(ch, begin)) != -1) { 1204 ++separatorCount; 1205 begin = end + 1; 1206 } 1207 int lastPartEnd = input.length(); 1208 if (limit == 0 && begin == lastPartEnd) { 1209 // Last part is empty for limit == 0, remove all trailing empty matches. 1210 if (separatorCount == lastPartEnd) { 1211 // Input contains only separators. 1212 return EmptyArray.STRING; 1213 } 1214 // Find the beginning of trailing separators. 1215 do { 1216 --begin; 1217 } while (input.charAt(begin - 1) == ch); 1218 // Reduce separatorCount and fix lastPartEnd. 1219 separatorCount -= input.length() - begin; 1220 lastPartEnd = begin; 1221 } 1222 1223 // Collect the result parts. 1224 String[] result = new String[separatorCount + 1]; 1225 begin = 0; 1226 for (int i = 0; i != separatorCount; ++i) { 1227 end = input.indexOf(ch, begin); 1228 result[i] = input.substring(begin, end); 1229 begin = end + 1; 1230 } 1231 // Add last part. 1232 result[separatorCount] = input.substring(begin, lastPartEnd); 1233 return result; 1234 } 1235 1236 /** 1237 * Splits the given input sequence around matches of this pattern. 1238 * 1239 * <p> This method works as if by invoking the two-argument {@link 1240 * #split(java.lang.CharSequence, int) split} method with the given input 1241 * sequence and a limit argument of zero. Trailing empty strings are 1242 * therefore not included in the resulting array. </p> 1243 * 1244 * <p> The input <tt>"boo:and:foo"</tt>, for example, yields the following 1245 * results with these expressions: 1246 * 1247 * <blockquote><table cellpadding=1 cellspacing=0 1248 * summary="Split examples showing regex and result"> 1249 * <tr><th><P align="left"><i>Regex </i></th> 1250 * <th><P align="left"><i>Result</i></th></tr> 1251 * <tr><td align=center>:</td> 1252 * <td><tt>{ "boo", "and", "foo" }</tt></td></tr> 1253 * <tr><td align=center>o</td> 1254 * <td><tt>{ "b", "", ":and:f" }</tt></td></tr> 1255 * </table></blockquote> 1256 * 1257 * 1258 * @param input 1259 * The character sequence to be split 1260 * 1261 * @return The array of strings computed by splitting the input 1262 * around matches of this pattern 1263 */ 1264 public String[] split(CharSequence input) { 1265 return split(input, 0); 1266 } 1267 1268 /** 1269 * Returns a literal pattern <code>String</code> for the specified 1270 * <code>String</code>. 1271 * 1272 * <p>This method produces a <code>String</code> that can be used to 1273 * create a <code>Pattern</code> that would match the string 1274 * <code>s</code> as if it were a literal pattern.</p> Metacharacters 1275 * or escape sequences in the input sequence will be given no special 1276 * meaning. 1277 * 1278 * @param s The string to be literalized 1279 * @return A literal string replacement 1280 * @since 1.5 1281 */ 1282 public static String quote(String s) { 1283 int slashEIndex = s.indexOf("\\E"); 1284 if (slashEIndex == -1) 1285 return "\\Q" + s + "\\E"; 1286 1287 StringBuilder sb = new StringBuilder(s.length() * 2); 1288 sb.append("\\Q"); 1289 slashEIndex = 0; 1290 int current = 0; 1291 while ((slashEIndex = s.indexOf("\\E", current)) != -1) { 1292 sb.append(s.substring(current, slashEIndex)); 1293 current = slashEIndex + 2; 1294 sb.append("\\E\\\\E\\Q"); 1295 } 1296 sb.append(s.substring(current, s.length())); 1297 sb.append("\\E"); 1298 return sb.toString(); 1299 } 1300 1301 /** 1302 * Recompile the Pattern instance from a stream. The original pattern 1303 * string is read in and the object tree is recompiled from it. 1304 */ 1305 private void readObject(java.io.ObjectInputStream s) 1306 throws java.io.IOException, ClassNotFoundException { 1307 1308 // Read in all fields 1309 s.defaultReadObject(); 1310 compile(); 1311 } 1312 1313 /** 1314 * This private constructor is used to create all Patterns. The pattern 1315 * string and match flags are all that is needed to completely describe 1316 * a Pattern. 1317 */ 1318 private Pattern(String p, int f) { 1319 if ((f & CANON_EQ) != 0) { 1320 throw new UnsupportedOperationException("CANON_EQ flag not supported"); 1321 } 1322 int supportedFlags = CASE_INSENSITIVE | COMMENTS | DOTALL | LITERAL | MULTILINE | UNICODE_CASE | UNIX_LINES; 1323 if ((f & ~supportedFlags) != 0) { 1324 throw new IllegalArgumentException("Unsupported flags: " + (f & ~supportedFlags)); 1325 } 1326 this.pattern = p; 1327 this.flags = f; 1328 compile(); 1329 } 1330 1331 private void compile() throws PatternSyntaxException { 1332 if (pattern == null) { 1333 throw new NullPointerException("pattern == null"); 1334 } 1335 1336 String icuPattern = pattern; 1337 if ((flags & LITERAL) != 0) { 1338 icuPattern = quote(pattern); 1339 } 1340 1341 // These are the flags natively supported by ICU. 1342 // They even have the same value in native code. 1343 int icuFlags = flags & (CASE_INSENSITIVE | COMMENTS | MULTILINE | DOTALL | UNIX_LINES); 1344 address = compileImpl(icuPattern, icuFlags); 1345 registry.registerNativeAllocation(this, address); 1346 } 1347 1348 private static native long compileImpl(String regex, int flags); 1349 private static native long getNativeFinalizer(); 1350 private static native int nativeSize(); 1351 1352 /** 1353 * Creates a predicate which can be used to match a string. 1354 * 1355 * @return The predicate which can be used for matching on a string 1356 * @since 1.8 1357 */ 1358 public Predicate<String> asPredicate() { 1359 return s -> matcher(s).find(); 1360 } 1361 1362 /** 1363 * Creates a stream from the given input sequence around matches of this 1364 * pattern. 1365 * 1366 * <p> The stream returned by this method contains each substring of the 1367 * input sequence that is terminated by another subsequence that matches 1368 * this pattern or is terminated by the end of the input sequence. The 1369 * substrings in the stream are in the order in which they occur in the 1370 * input. Trailing empty strings will be discarded and not encountered in 1371 * the stream. 1372 * 1373 * <p> If this pattern does not match any subsequence of the input then 1374 * the resulting stream has just one element, namely the input sequence in 1375 * string form. 1376 * 1377 * <p> When there is a positive-width match at the beginning of the input 1378 * sequence then an empty leading substring is included at the beginning 1379 * of the stream. A zero-width match at the beginning however never produces 1380 * such empty leading substring. 1381 * 1382 * <p> If the input sequence is mutable, it must remain constant during the 1383 * execution of the terminal stream operation. Otherwise, the result of the 1384 * terminal stream operation is undefined. 1385 * 1386 * @param input 1387 * The character sequence to be split 1388 * 1389 * @return The stream of strings computed by splitting the input 1390 * around matches of this pattern 1391 * @see #split(CharSequence) 1392 * @since 1.8 1393 */ 1394 public Stream<String> splitAsStream(final CharSequence input) { 1395 class MatcherIterator implements Iterator<String> { 1396 private final Matcher matcher; 1397 // The start position of the next sub-sequence of input 1398 // when current == input.length there are no more elements 1399 private int current; 1400 // null if the next element, if any, needs to obtained 1401 private String nextElement; 1402 // > 0 if there are N next empty elements 1403 private int emptyElementCount; 1404 1405 MatcherIterator() { 1406 this.matcher = matcher(input); 1407 } 1408 1409 public String next() { 1410 if (!hasNext()) 1411 throw new NoSuchElementException(); 1412 1413 if (emptyElementCount == 0) { 1414 String n = nextElement; 1415 nextElement = null; 1416 return n; 1417 } else { 1418 emptyElementCount--; 1419 return ""; 1420 } 1421 } 1422 1423 public boolean hasNext() { 1424 if (nextElement != null || emptyElementCount > 0) 1425 return true; 1426 1427 if (current == input.length()) 1428 return false; 1429 1430 // Consume the next matching element 1431 // Count sequence of matching empty elements 1432 while (matcher.find()) { 1433 nextElement = input.subSequence(current, matcher.start()).toString(); 1434 current = matcher.end(); 1435 if (!nextElement.isEmpty()) { 1436 return true; 1437 } else if (current > 0) { // no empty leading substring for zero-width 1438 // match at the beginning of the input 1439 emptyElementCount++; 1440 } 1441 } 1442 1443 // Consume last matching element 1444 nextElement = input.subSequence(current, input.length()).toString(); 1445 current = input.length(); 1446 if (!nextElement.isEmpty()) { 1447 return true; 1448 } else { 1449 // Ignore a terminal sequence of matching empty elements 1450 emptyElementCount = 0; 1451 nextElement = null; 1452 return false; 1453 } 1454 } 1455 } 1456 return StreamSupport.stream(Spliterators.spliteratorUnknownSize( 1457 new MatcherIterator(), Spliterator.ORDERED | Spliterator.NONNULL), false); 1458 } 1459} 1460