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