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