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 dalvik.annotation.optimization.ReachabilitySensitive; 30 import libcore.util.NativeAllocationRegistry; 31 32 /** 33 * An engine that performs match operations on a {@linkplain java.lang.CharSequence 34 * character sequence} by interpreting a {@link Pattern}. 35 * 36 * <p> A matcher is created from a pattern by invoking the pattern's {@link 37 * Pattern#matcher matcher} method. Once created, a matcher can be used to 38 * perform three different kinds of match operations: 39 * 40 * <ul> 41 * 42 * <li><p> The {@link #matches matches} method attempts to match the entire 43 * input sequence against the pattern. </p></li> 44 * 45 * <li><p> The {@link #lookingAt lookingAt} method attempts to match the 46 * input sequence, starting at the beginning, against the pattern. </p></li> 47 * 48 * <li><p> The {@link #find find} method scans the input sequence looking for 49 * the next subsequence that matches the pattern. </p></li> 50 * 51 * </ul> 52 * 53 * <p> Each of these methods returns a boolean indicating success or failure. 54 * More information about a successful match can be obtained by querying the 55 * state of the matcher. 56 * 57 * <p> A matcher finds matches in a subset of its input called the 58 * <i>region</i>. By default, the region contains all of the matcher's input. 59 * The region can be modified via the{@link #region region} method and queried 60 * via the {@link #regionStart regionStart} and {@link #regionEnd regionEnd} 61 * methods. The way that the region boundaries interact with some pattern 62 * constructs can be changed. See {@link #useAnchoringBounds 63 * useAnchoringBounds} and {@link #useTransparentBounds useTransparentBounds} 64 * for more details. 65 * 66 * <p> This class also defines methods for replacing matched subsequences with 67 * new strings whose contents can, if desired, be computed from the match 68 * result. The {@link #appendReplacement appendReplacement} and {@link 69 * #appendTail appendTail} methods can be used in tandem in order to collect 70 * the result into an existing string buffer, or the more convenient {@link 71 * #replaceAll replaceAll} method can be used to create a string in which every 72 * matching subsequence in the input sequence is replaced. 73 * 74 * <p> The explicit state of a matcher includes the start and end indices of 75 * the most recent successful match. It also includes the start and end 76 * indices of the input subsequence captured by each <a 77 * href="Pattern.html#cg">capturing group</a> in the pattern as well as a total 78 * count of such subsequences. As a convenience, methods are also provided for 79 * returning these captured subsequences in string form. 80 * 81 * <p> The explicit state of a matcher is initially undefined; attempting to 82 * query any part of it before a successful match will cause an {@link 83 * IllegalStateException} to be thrown. The explicit state of a matcher is 84 * recomputed by every match operation. 85 * 86 * <p> The implicit state of a matcher includes the input character sequence as 87 * well as the <i>append position</i>, which is initially zero and is updated 88 * by the {@link #appendReplacement appendReplacement} method. 89 * 90 * <p> A matcher may be reset explicitly by invoking its {@link #reset()} 91 * method or, if a new input sequence is desired, its {@link 92 * #reset(java.lang.CharSequence) reset(CharSequence)} method. Resetting a 93 * matcher discards its explicit state information and sets the append position 94 * to zero. 95 * 96 * <p> Instances of this class are not safe for use by multiple concurrent 97 * threads. </p> 98 * 99 * 100 * @author Mike McCloskey 101 * @author Mark Reinhold 102 * @author JSR-51 Expert Group 103 * @since 1.4 104 * @spec JSR-51 105 */ 106 107 public final class Matcher implements MatchResult { 108 109 /** 110 * The Pattern object that created this Matcher. 111 */ 112 // Patterns also contain cleanup code and a ReachabilitySensitive field. 113 // This ensures that "this" and pattern remain reachable while we're using pattern.address 114 // directly. 115 @ReachabilitySensitive 116 private Pattern parentPattern; 117 118 /** 119 * Holds the offsets for the most recent match. 120 */ 121 int[] groups; 122 123 /** 124 * The range within the sequence that is to be matched (between 0 125 * and text.length()). 126 */ 127 int from, to; 128 129 /** 130 * Holds the input text. 131 */ 132 String text; 133 134 /** 135 * Reflects whether a match has been found during the most recent find 136 * operation. 137 */ 138 private boolean matchFound; 139 140 /** 141 * The address of the native peer. 142 * Uses of this must be manually synchronized to avoid native crashes. 143 */ 144 @ReachabilitySensitive 145 private long address; 146 147 /** 148 * If non-null, a Runnable that can be used to explicitly deallocate address. 149 */ 150 private Runnable nativeFinalizer; 151 152 private static final NativeAllocationRegistry registry = 153 NativeAllocationRegistry.createMalloced(Matcher.class.getClassLoader(), 154 getNativeFinalizer()); 155 156 /** 157 * The index of the last position appended in a substitution. 158 */ 159 int appendPos = 0; 160 161 /** 162 * Holds the original CharSequence for use in {@link #reset}. {@link #text} is used during 163 * matching. Note that CharSequence is mutable while String is not, so reset can cause the input 164 * to match to change. 165 */ 166 private CharSequence originalInput; 167 168 /** 169 * If transparentBounds is true then the boundaries of this 170 * matcher's region are transparent to lookahead, lookbehind, 171 * and boundary matching constructs that try to see beyond them. 172 */ 173 boolean transparentBounds = false; 174 175 /** 176 * If anchoringBounds is true then the boundaries of this 177 * matcher's region match anchors such as ^ and $. 178 */ 179 boolean anchoringBounds = true; 180 181 /** 182 * All matchers have the state used by Pattern during a match. 183 */ Matcher(Pattern parent, CharSequence text)184 Matcher(Pattern parent, CharSequence text) { 185 usePattern(parent); 186 reset(text); 187 } 188 189 /** 190 * Returns the pattern that is interpreted by this matcher. 191 * 192 * @return The pattern for which this matcher was created 193 */ pattern()194 public Pattern pattern() { 195 return parentPattern; 196 } 197 198 /** 199 * Returns the match state of this matcher as a {@link MatchResult}. 200 * The result is unaffected by subsequent operations performed upon this 201 * matcher. 202 * 203 * @return a <code>MatchResult</code> with the state of this matcher 204 * @since 1.5 205 */ toMatchResult()206 public MatchResult toMatchResult() { 207 ensureMatch(); 208 return new OffsetBasedMatchResult(text, groups); 209 } 210 211 /** 212 * Changes the <tt>Pattern</tt> that this <tt>Matcher</tt> uses to 213 * find matches with. 214 * 215 * <p> This method causes this matcher to lose information 216 * about the groups of the last match that occurred. The 217 * matcher's position in the input is maintained and its 218 * last append position is unaffected.</p> 219 * 220 * @param newPattern 221 * The new pattern used by this matcher 222 * @return This matcher 223 * @throws IllegalArgumentException 224 * If newPattern is <tt>null</tt> 225 * @since 1.5 226 */ usePattern(Pattern newPattern)227 public Matcher usePattern(Pattern newPattern) { 228 if (newPattern == null) 229 throw new IllegalArgumentException("Pattern cannot be null"); 230 parentPattern = newPattern; 231 232 synchronized (this) { 233 if (nativeFinalizer != null) { 234 nativeFinalizer.run(); 235 address = 0; // In case openImpl throws. 236 nativeFinalizer = null; 237 } 238 address = openImpl(parentPattern.address); 239 nativeFinalizer = registry.registerNativeAllocation(this, address); 240 } 241 242 if (text != null) { 243 resetForInput(); 244 } 245 246 groups = new int[(groupCount() + 1) * 2]; 247 matchFound = false; 248 return this; 249 } 250 251 /** 252 * Resets this matcher. 253 * 254 * <p> Resetting a matcher discards all of its explicit state information 255 * and sets its append position to zero. The matcher's region is set to the 256 * default region, which is its entire character sequence. The anchoring 257 * and transparency of this matcher's region boundaries are unaffected. 258 * 259 * @return This matcher 260 */ reset()261 public Matcher reset() { 262 return reset(originalInput, 0, originalInput.length()); 263 } 264 265 /** 266 * Resets this matcher with a new input sequence. 267 * 268 * <p> Resetting a matcher discards all of its explicit state information 269 * and sets its append position to zero. The matcher's region is set to 270 * the default region, which is its entire character sequence. The 271 * anchoring and transparency of this matcher's region boundaries are 272 * unaffected. 273 * 274 * @param input 275 * The new input character sequence 276 * 277 * @return This matcher 278 */ reset(CharSequence input)279 public Matcher reset(CharSequence input) { 280 return reset(input, 0, input.length()); 281 } 282 283 /** 284 * Returns the start index of the previous match. 285 * 286 * @return The index of the first character matched 287 * 288 * @throws IllegalStateException 289 * If no match has yet been attempted, 290 * or if the previous match operation failed 291 */ start()292 public int start() { 293 return start(0); 294 } 295 296 /** 297 * Returns the start index of the subsequence captured by the given group 298 * during the previous match operation. 299 * 300 * <p> <a href="Pattern.html#cg">Capturing groups</a> are indexed from left 301 * to right, starting at one. Group zero denotes the entire pattern, so 302 * the expression <i>m.</i><tt>start(0)</tt> is equivalent to 303 * <i>m.</i><tt>start()</tt>. </p> 304 * 305 * @param group 306 * The index of a capturing group in this matcher's pattern 307 * 308 * @return The index of the first character captured by the group, 309 * or <tt>-1</tt> if the match was successful but the group 310 * itself did not match anything 311 * 312 * @throws IllegalStateException 313 * If no match has yet been attempted, 314 * or if the previous match operation failed 315 * 316 * @throws IndexOutOfBoundsException 317 * If there is no capturing group in the pattern 318 * with the given index 319 */ start(int group)320 public int start(int group) { 321 ensureMatch(); 322 if (group < 0 || group > groupCount()) 323 throw new IndexOutOfBoundsException("No group " + group); 324 return groups[group * 2]; 325 } 326 327 /** 328 * Returns the start index of the subsequence captured by the given 329 * <a href="Pattern.html#groupname">named-capturing group</a> during the 330 * previous match operation. 331 * 332 * @param name 333 * The name of a named-capturing group in this matcher's pattern 334 * 335 * @return The index of the first character captured by the group, 336 * or {@code -1} if the match was successful but the group 337 * itself did not match anything 338 * 339 * @throws IllegalStateException 340 * If no match has yet been attempted, 341 * or if the previous match operation failed 342 * 343 * @throws IllegalArgumentException 344 * If there is no capturing group in the pattern 345 * with the given name 346 * @since 1.8 347 */ start(String name)348 public int start(String name) { 349 return groups[getMatchedGroupIndex(name) * 2]; 350 } 351 352 /** 353 * Returns the offset after the last character matched. 354 * 355 * @return The offset after the last character matched 356 * 357 * @throws IllegalStateException 358 * If no match has yet been attempted, 359 * or if the previous match operation failed 360 */ end()361 public int end() { 362 return end(0); 363 } 364 365 /** 366 * Returns the offset after the last character of the subsequence 367 * captured by the given group during the previous match operation. 368 * 369 * <p> <a href="Pattern.html#cg">Capturing groups</a> are indexed from left 370 * to right, starting at one. Group zero denotes the entire pattern, so 371 * the expression <i>m.</i><tt>end(0)</tt> is equivalent to 372 * <i>m.</i><tt>end()</tt>. </p> 373 * 374 * @param group 375 * The index of a capturing group in this matcher's pattern 376 * 377 * @return The offset after the last character captured by the group, 378 * or <tt>-1</tt> if the match was successful 379 * but the group itself did not match anything 380 * 381 * @throws IllegalStateException 382 * If no match has yet been attempted, 383 * or if the previous match operation failed 384 * 385 * @throws IndexOutOfBoundsException 386 * If there is no capturing group in the pattern 387 * with the given index 388 */ end(int group)389 public int end(int group) { 390 ensureMatch(); 391 if (group < 0 || group > groupCount()) 392 throw new IndexOutOfBoundsException("No group " + group); 393 return groups[group * 2 + 1]; 394 } 395 396 /** 397 * Returns the offset after the last character of the subsequence 398 * captured by the given <a href="Pattern.html#groupname">named-capturing 399 * group</a> during the previous match operation. 400 * 401 * @param name 402 * The name of a named-capturing group in this matcher's pattern 403 * 404 * @return The offset after the last character captured by the group, 405 * or {@code -1} if the match was successful 406 * but the group itself did not match anything 407 * 408 * @throws IllegalStateException 409 * If no match has yet been attempted, 410 * or if the previous match operation failed 411 * 412 * @throws IllegalArgumentException 413 * If there is no capturing group in the pattern 414 * with the given name 415 * @since 1.8 416 */ end(String name)417 public int end(String name) { 418 return groups[getMatchedGroupIndex(name) * 2 + 1]; 419 } 420 421 /** 422 * Returns the input subsequence matched by the previous match. 423 * 424 * <p> For a matcher <i>m</i> with input sequence <i>s</i>, 425 * the expressions <i>m.</i><tt>group()</tt> and 426 * <i>s.</i><tt>substring(</tt><i>m.</i><tt>start(),</tt> <i>m.</i><tt>end())</tt> 427 * are equivalent. </p> 428 * 429 * <p> Note that some patterns, for example <tt>a*</tt>, match the empty 430 * string. This method will return the empty string when the pattern 431 * successfully matches the empty string in the input. </p> 432 * 433 * @return The (possibly empty) subsequence matched by the previous match, 434 * in string form 435 * 436 * @throws IllegalStateException 437 * If no match has yet been attempted, 438 * or if the previous match operation failed 439 */ group()440 public String group() { 441 return group(0); 442 } 443 444 /** 445 * Returns the input subsequence captured by the given group during the 446 * previous match operation. 447 * 448 * <p> For a matcher <i>m</i>, input sequence <i>s</i>, and group index 449 * <i>g</i>, the expressions <i>m.</i><tt>group(</tt><i>g</i><tt>)</tt> and 450 * <i>s.</i><tt>substring(</tt><i>m.</i><tt>start(</tt><i>g</i><tt>),</tt> <i>m.</i><tt>end(</tt><i>g</i><tt>))</tt> 451 * are equivalent. </p> 452 * 453 * <p> <a href="Pattern.html#cg">Capturing groups</a> are indexed from left 454 * to right, starting at one. Group zero denotes the entire pattern, so 455 * the expression <tt>m.group(0)</tt> is equivalent to <tt>m.group()</tt>. 456 * </p> 457 * 458 * <p> If the match was successful but the group specified failed to match 459 * any part of the input sequence, then <tt>null</tt> is returned. Note 460 * that some groups, for example <tt>(a*)</tt>, match the empty string. 461 * This method will return the empty string when such a group successfully 462 * matches the empty string in the input. </p> 463 * 464 * @param group 465 * The index of a capturing group in this matcher's pattern 466 * 467 * @return The (possibly empty) subsequence captured by the group 468 * during the previous match, or <tt>null</tt> if the group 469 * failed to match part of the input 470 * 471 * @throws IllegalStateException 472 * If no match has yet been attempted, 473 * or if the previous match operation failed 474 * 475 * @throws IndexOutOfBoundsException 476 * If there is no capturing group in the pattern 477 * with the given index 478 */ group(int group)479 public String group(int group) { 480 ensureMatch(); 481 if (group < 0 || group > groupCount()) 482 throw new IndexOutOfBoundsException("No group " + group); 483 if ((groups[group*2] == -1) || (groups[group*2+1] == -1)) 484 return null; 485 return getSubSequence(groups[group * 2], groups[group * 2 + 1]).toString(); 486 } 487 488 /** 489 * Returns the input subsequence captured by the given 490 * <a href="Pattern.html#groupname">named-capturing group</a> during the previous 491 * match operation. 492 * 493 * <p> If the match was successful but the group specified failed to match 494 * any part of the input sequence, then <tt>null</tt> is returned. Note 495 * that some groups, for example <tt>(a*)</tt>, match the empty string. 496 * This method will return the empty string when such a group successfully 497 * matches the empty string in the input. </p> 498 * 499 * @param name 500 * The name of a named-capturing group in this matcher's pattern 501 * 502 * @return The (possibly empty) subsequence captured by the named group 503 * during the previous match, or <tt>null</tt> if the group 504 * failed to match part of the input 505 * 506 * @throws IllegalStateException 507 * If no match has yet been attempted, 508 * or if the previous match operation failed 509 * 510 * @throws IllegalArgumentException 511 * If there is no capturing group in the pattern 512 * with the given name 513 * @since 1.7 514 */ group(String name)515 public String group(String name) { 516 int group = getMatchedGroupIndex(name); 517 if ((groups[group*2] == -1) || (groups[group*2+1] == -1)) 518 return null; 519 return getSubSequence(groups[group * 2], groups[group * 2 + 1]).toString(); 520 } 521 522 /** 523 * Returns the number of capturing groups in this matcher's pattern. 524 * 525 * <p> Group zero denotes the entire pattern by convention. It is not 526 * included in this count. 527 * 528 * <p> Any non-negative integer smaller than or equal to the value 529 * returned by this method is guaranteed to be a valid group index for 530 * this matcher. </p> 531 * 532 * @return The number of capturing groups in this matcher's pattern 533 */ groupCount()534 public int groupCount() { 535 synchronized (this) { 536 return groupCountImpl(address); 537 } 538 } 539 540 /** 541 * Attempts to match the entire region against the pattern. 542 * 543 * <p> If the match succeeds then more information can be obtained via the 544 * <tt>start</tt>, <tt>end</tt>, and <tt>group</tt> methods. </p> 545 * 546 * @return <tt>true</tt> if, and only if, the entire region sequence 547 * matches this matcher's pattern 548 */ matches()549 public boolean matches() { 550 synchronized (this) { 551 matchFound = matchesImpl(address, groups); 552 } 553 return matchFound; 554 } 555 556 /** 557 * Attempts to find the next subsequence of the input sequence that matches 558 * the pattern. 559 * 560 * <p> This method starts at the beginning of this matcher's region, or, if 561 * a previous invocation of the method was successful and the matcher has 562 * not since been reset, at the first character not matched by the previous 563 * match. 564 * 565 * <p> If the match succeeds then more information can be obtained via the 566 * <tt>start</tt>, <tt>end</tt>, and <tt>group</tt> methods. </p> 567 * 568 * @return <tt>true</tt> if, and only if, a subsequence of the input 569 * sequence matches this matcher's pattern 570 */ find()571 public boolean find() { 572 synchronized (this) { 573 matchFound = findNextImpl(address, groups); 574 } 575 return matchFound; 576 } 577 578 /** 579 * Resets this matcher and then attempts to find the next subsequence of 580 * the input sequence that matches the pattern, starting at the specified 581 * index. 582 * 583 * <p> If the match succeeds then more information can be obtained via the 584 * <tt>start</tt>, <tt>end</tt>, and <tt>group</tt> methods, and subsequent 585 * invocations of the {@link #find()} method will start at the first 586 * character not matched by this match. </p> 587 * 588 * @param start the index to start searching for a match 589 * @throws IndexOutOfBoundsException 590 * If start is less than zero or if start is greater than the 591 * length of the input sequence. 592 * 593 * @return <tt>true</tt> if, and only if, a subsequence of the input 594 * sequence starting at the given index matches this matcher's 595 * pattern 596 */ find(int start)597 public boolean find(int start) { 598 int limit = getTextLength(); 599 if ((start < 0) || (start > limit)) 600 throw new IndexOutOfBoundsException("Illegal start index"); 601 reset(); 602 synchronized (this) { 603 matchFound = findImpl(address, start, groups); 604 } 605 return matchFound; 606 } 607 608 /** 609 * Attempts to match the input sequence, starting at the beginning of the 610 * region, against the pattern. 611 * 612 * <p> Like the {@link #matches matches} method, this method always starts 613 * at the beginning of the region; unlike that method, it does not 614 * require that the entire region be matched. 615 * 616 * <p> If the match succeeds then more information can be obtained via the 617 * <tt>start</tt>, <tt>end</tt>, and <tt>group</tt> methods. </p> 618 * 619 * @return <tt>true</tt> if, and only if, a prefix of the input 620 * sequence matches this matcher's pattern 621 */ lookingAt()622 public boolean lookingAt() { 623 synchronized (this) { 624 matchFound = lookingAtImpl(address, groups); 625 } 626 return matchFound; 627 } 628 629 /** 630 * Returns a literal replacement <code>String</code> for the specified 631 * <code>String</code>. 632 * 633 * This method produces a <code>String</code> that will work 634 * as a literal replacement <code>s</code> in the 635 * <code>appendReplacement</code> method of the {@link Matcher} class. 636 * The <code>String</code> produced will match the sequence of characters 637 * in <code>s</code> treated as a literal sequence. Slashes ('\') and 638 * dollar signs ('$') will be given no special meaning. 639 * 640 * @param s The string to be literalized 641 * @return A literal string replacement 642 * @since 1.5 643 */ quoteReplacement(String s)644 public static String quoteReplacement(String s) { 645 if ((s.indexOf('\\') == -1) && (s.indexOf('$') == -1)) 646 return s; 647 StringBuilder sb = new StringBuilder(); 648 for (int i=0; i<s.length(); i++) { 649 char c = s.charAt(i); 650 if (c == '\\' || c == '$') { 651 sb.append('\\'); 652 } 653 sb.append(c); 654 } 655 return sb.toString(); 656 } 657 658 /** 659 * Implements a non-terminal append-and-replace step. 660 * 661 * <p> This method performs the following actions: </p> 662 * 663 * <ol> 664 * 665 * <li><p> It reads characters from the input sequence, starting at the 666 * append position, and appends them to the given string buffer. It 667 * stops after reading the last character preceding the previous match, 668 * that is, the character at index {@link 669 * #start()} <tt>-</tt> <tt>1</tt>. </p></li> 670 * 671 * <li><p> It appends the given replacement string to the string buffer. 672 * </p></li> 673 * 674 * <li><p> It sets the append position of this matcher to the index of 675 * the last character matched, plus one, that is, to {@link #end()}. 676 * </p></li> 677 * 678 * </ol> 679 * 680 * <p> The replacement string may contain references to subsequences 681 * captured during the previous match: Each occurrence of 682 * <tt>${</tt><i>name</i><tt>}</tt> or <tt>$</tt><i>g</i> 683 * will be replaced by the result of evaluating the corresponding 684 * {@link #group(String) group(name)} or {@link #group(int) group(g)} 685 * respectively. For <tt>$</tt><i>g</i>, 686 * the first number after the <tt>$</tt> is always treated as part of 687 * the group reference. Subsequent numbers are incorporated into g if 688 * they would form a legal group reference. Only the numerals '0' 689 * through '9' are considered as potential components of the group 690 * reference. If the second group matched the string <tt>"foo"</tt>, for 691 * example, then passing the replacement string <tt>"$2bar"</tt> would 692 * cause <tt>"foobar"</tt> to be appended to the string buffer. A dollar 693 * sign (<tt>$</tt>) may be included as a literal in the replacement 694 * string by preceding it with a backslash (<tt>\$</tt>). 695 * 696 * <p> Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in 697 * the replacement string may cause the results to be different than if it 698 * were being treated as a literal replacement string. Dollar signs may be 699 * treated as references to captured subsequences as described above, and 700 * backslashes are used to escape literal characters in the replacement 701 * string. 702 * 703 * <p> This method is intended to be used in a loop together with the 704 * {@link #appendTail appendTail} and {@link #find find} methods. The 705 * following code, for example, writes <tt>one dog two dogs in the 706 * yard</tt> to the standard-output stream: </p> 707 * 708 * <blockquote><pre> 709 * Pattern p = Pattern.compile("cat"); 710 * Matcher m = p.matcher("one cat two cats in the yard"); 711 * StringBuffer sb = new StringBuffer(); 712 * while (m.find()) { 713 * m.appendReplacement(sb, "dog"); 714 * } 715 * m.appendTail(sb); 716 * System.out.println(sb.toString());</pre></blockquote> 717 * 718 * @param sb 719 * The target string buffer 720 * 721 * @param replacement 722 * The replacement string 723 * 724 * @return This matcher 725 * 726 * @throws IllegalStateException 727 * If no match has yet been attempted, 728 * or if the previous match operation failed 729 * 730 * @throws IllegalArgumentException 731 * If the replacement string refers to a named-capturing 732 * group that does not exist in the pattern 733 * 734 * @throws IndexOutOfBoundsException 735 * If the replacement string refers to a capturing group 736 * that does not exist in the pattern 737 */ appendReplacement(StringBuffer sb, String replacement)738 public Matcher appendReplacement(StringBuffer sb, String replacement) { 739 740 sb.append(text.substring(appendPos, start())); 741 appendEvaluated(sb, replacement); 742 appendPos = end(); 743 744 return this; 745 } 746 747 /** 748 * Internal helper method to append a given string to a given string buffer. 749 * If the string contains any references to groups, these are replaced by 750 * the corresponding group's contents. 751 * 752 * @param buffer the string buffer. 753 * @param s the string to append. 754 */ appendEvaluated(StringBuffer buffer, String s)755 private void appendEvaluated(StringBuffer buffer, String s) { 756 boolean escape = false; 757 boolean dollar = false; 758 boolean escapeNamedGroup = false; 759 int escapeNamedGroupStart = -1; 760 761 for (int i = 0; i < s.length(); i++) { 762 char c = s.charAt(i); 763 if (c == '\\' && !escape) { 764 escape = true; 765 } else if (c == '$' && !escape) { 766 dollar = true; 767 } else if (c >= '0' && c <= '9' && dollar) { 768 buffer.append(group(c - '0')); 769 dollar = false; 770 } else if (c == '{' && dollar) { 771 escapeNamedGroup = true; 772 escapeNamedGroupStart = i; 773 } else if (c == '}' && dollar && escapeNamedGroup) { 774 String namedGroupName = 775 s.substring(escapeNamedGroupStart + 1, i); 776 buffer.append(group(namedGroupName)); 777 dollar = false; 778 escapeNamedGroup = false; 779 } else if (c != '}' && dollar && escapeNamedGroup) { 780 continue; 781 } else { 782 buffer.append(c); 783 dollar = false; 784 escape = false; 785 escapeNamedGroup = false; 786 } 787 } 788 789 if (escape) { 790 throw new IllegalArgumentException("character to be escaped is missing"); 791 } 792 793 if (dollar) { 794 throw new IllegalArgumentException("Illegal group reference: group index is missing"); 795 } 796 797 if (escapeNamedGroup) { 798 throw new IllegalArgumentException("Missing ending brace '}' from replacement string"); 799 } 800 } 801 802 /** 803 * Implements a terminal append-and-replace step. 804 * 805 * <p> This method reads characters from the input sequence, starting at 806 * the append position, and appends them to the given string buffer. It is 807 * intended to be invoked after one or more invocations of the {@link 808 * #appendReplacement appendReplacement} method in order to copy the 809 * remainder of the input sequence. </p> 810 * 811 * @param sb 812 * The target string buffer 813 * 814 * @return The target string buffer 815 */ appendTail(StringBuffer sb)816 public StringBuffer appendTail(StringBuffer sb) { 817 if (appendPos < to) { 818 sb.append(text.substring(appendPos, to)); 819 } 820 return sb; 821 } 822 823 /** 824 * Replaces every subsequence of the input sequence that matches the 825 * pattern with the given replacement string. 826 * 827 * <p> This method first resets this matcher. It then scans the input 828 * sequence looking for matches of the pattern. Characters that are not 829 * part of any match are appended directly to the result string; each match 830 * is replaced in the result by the replacement string. The replacement 831 * string may contain references to captured subsequences as in the {@link 832 * #appendReplacement appendReplacement} method. 833 * 834 * <p> Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in 835 * the replacement string may cause the results to be different than if it 836 * were being treated as a literal replacement string. Dollar signs may be 837 * treated as references to captured subsequences as described above, and 838 * backslashes are used to escape literal characters in the replacement 839 * string. 840 * 841 * <p> Given the regular expression <tt>a*b</tt>, the input 842 * <tt>"aabfooaabfooabfoob"</tt>, and the replacement string 843 * <tt>"-"</tt>, an invocation of this method on a matcher for that 844 * expression would yield the string <tt>"-foo-foo-foo-"</tt>. 845 * 846 * <p> Invoking this method changes this matcher's state. If the matcher 847 * is to be used in further matching operations then it should first be 848 * reset. </p> 849 * 850 * @param replacement 851 * The replacement string 852 * 853 * @return The string constructed by replacing each matching subsequence 854 * by the replacement string, substituting captured subsequences 855 * as needed 856 */ replaceAll(String replacement)857 public String replaceAll(String replacement) { 858 reset(); 859 boolean result = find(); 860 if (result) { 861 StringBuffer sb = new StringBuffer(); 862 do { 863 appendReplacement(sb, replacement); 864 result = find(); 865 } while (result); 866 appendTail(sb); 867 return sb.toString(); 868 } 869 return text.toString(); 870 } 871 872 /** 873 * Replaces the first subsequence of the input sequence that matches the 874 * pattern with the given replacement string. 875 * 876 * <p> This method first resets this matcher. It then scans the input 877 * sequence looking for a match of the pattern. Characters that are not 878 * part of the match are appended directly to the result string; the match 879 * is replaced in the result by the replacement string. The replacement 880 * string may contain references to captured subsequences as in the {@link 881 * #appendReplacement appendReplacement} method. 882 * 883 * <p>Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in 884 * the replacement string may cause the results to be different than if it 885 * were being treated as a literal replacement string. Dollar signs may be 886 * treated as references to captured subsequences as described above, and 887 * backslashes are used to escape literal characters in the replacement 888 * string. 889 * 890 * <p> Given the regular expression <tt>dog</tt>, the input 891 * <tt>"zzzdogzzzdogzzz"</tt>, and the replacement string 892 * <tt>"cat"</tt>, an invocation of this method on a matcher for that 893 * expression would yield the string <tt>"zzzcatzzzdogzzz"</tt>. </p> 894 * 895 * <p> Invoking this method changes this matcher's state. If the matcher 896 * is to be used in further matching operations then it should first be 897 * reset. </p> 898 * 899 * @param replacement 900 * The replacement string 901 * @return The string constructed by replacing the first matching 902 * subsequence by the replacement string, substituting captured 903 * subsequences as needed 904 */ replaceFirst(String replacement)905 public String replaceFirst(String replacement) { 906 if (replacement == null) 907 throw new NullPointerException("replacement"); 908 reset(); 909 if (!find()) 910 return text.toString(); 911 StringBuffer sb = new StringBuffer(); 912 appendReplacement(sb, replacement); 913 appendTail(sb); 914 return sb.toString(); 915 } 916 917 /** 918 * Sets the limits of this matcher's region. The region is the part of the 919 * input sequence that will be searched to find a match. Invoking this 920 * method resets the matcher, and then sets the region to start at the 921 * index specified by the <code>start</code> parameter and end at the 922 * index specified by the <code>end</code> parameter. 923 * 924 * <p>Depending on the transparency and anchoring being used (see 925 * {@link #useTransparentBounds useTransparentBounds} and 926 * {@link #useAnchoringBounds useAnchoringBounds}), certain constructs such 927 * as anchors may behave differently at or around the boundaries of the 928 * region. 929 * 930 * @param start 931 * The index to start searching at (inclusive) 932 * @param end 933 * The index to end searching at (exclusive) 934 * @throws IndexOutOfBoundsException 935 * If start or end is less than zero, if 936 * start is greater than the length of the input sequence, if 937 * end is greater than the length of the input sequence, or if 938 * start is greater than end. 939 * @return this matcher 940 * @since 1.5 941 */ region(int start, int end)942 public Matcher region(int start, int end) { 943 return reset(originalInput, start, end); 944 } 945 946 /** 947 * Reports the start index of this matcher's region. The 948 * searches this matcher conducts are limited to finding matches 949 * within {@link #regionStart regionStart} (inclusive) and 950 * {@link #regionEnd regionEnd} (exclusive). 951 * 952 * @return The starting point of this matcher's region 953 * @since 1.5 954 */ regionStart()955 public int regionStart() { 956 return from; 957 } 958 959 /** 960 * Reports the end index (exclusive) of this matcher's region. 961 * The searches this matcher conducts are limited to finding matches 962 * within {@link #regionStart regionStart} (inclusive) and 963 * {@link #regionEnd regionEnd} (exclusive). 964 * 965 * @return the ending point of this matcher's region 966 * @since 1.5 967 */ regionEnd()968 public int regionEnd() { 969 return to; 970 } 971 972 /** 973 * Queries the transparency of region bounds for this matcher. 974 * 975 * <p> This method returns <tt>true</tt> if this matcher uses 976 * <i>transparent</i> bounds, <tt>false</tt> if it uses <i>opaque</i> 977 * bounds. 978 * 979 * <p> See {@link #useTransparentBounds useTransparentBounds} for a 980 * description of transparent and opaque bounds. 981 * 982 * <p> By default, a matcher uses opaque region boundaries. 983 * 984 * @return <tt>true</tt> iff this matcher is using transparent bounds, 985 * <tt>false</tt> otherwise. 986 * @see java.util.regex.Matcher#useTransparentBounds(boolean) 987 * @since 1.5 988 */ hasTransparentBounds()989 public boolean hasTransparentBounds() { 990 return transparentBounds; 991 } 992 993 /** 994 * Sets the transparency of region bounds for this matcher. 995 * 996 * <p> Invoking this method with an argument of <tt>true</tt> will set this 997 * matcher to use <i>transparent</i> bounds. If the boolean 998 * argument is <tt>false</tt>, then <i>opaque</i> bounds will be used. 999 * 1000 * <p> Using transparent bounds, the boundaries of this 1001 * matcher's region are transparent to lookahead, lookbehind, 1002 * and boundary matching constructs. Those constructs can see beyond the 1003 * boundaries of the region to see if a match is appropriate. 1004 * 1005 * <p> Using opaque bounds, the boundaries of this matcher's 1006 * region are opaque to lookahead, lookbehind, and boundary matching 1007 * constructs that may try to see beyond them. Those constructs cannot 1008 * look past the boundaries so they will fail to match anything outside 1009 * of the region. 1010 * 1011 * <p> By default, a matcher uses opaque bounds. 1012 * 1013 * @param b a boolean indicating whether to use opaque or transparent 1014 * regions 1015 * @return this matcher 1016 * @see java.util.regex.Matcher#hasTransparentBounds 1017 * @since 1.5 1018 */ useTransparentBounds(boolean b)1019 public Matcher useTransparentBounds(boolean b) { 1020 synchronized (this) { 1021 transparentBounds = b; 1022 useTransparentBoundsImpl(address, b); 1023 } 1024 return this; 1025 } 1026 1027 /** 1028 * Queries the anchoring of region bounds for this matcher. 1029 * 1030 * <p> This method returns <tt>true</tt> if this matcher uses 1031 * <i>anchoring</i> bounds, <tt>false</tt> otherwise. 1032 * 1033 * <p> See {@link #useAnchoringBounds useAnchoringBounds} for a 1034 * description of anchoring bounds. 1035 * 1036 * <p> By default, a matcher uses anchoring region boundaries. 1037 * 1038 * @return <tt>true</tt> iff this matcher is using anchoring bounds, 1039 * <tt>false</tt> otherwise. 1040 * @see java.util.regex.Matcher#useAnchoringBounds(boolean) 1041 * @since 1.5 1042 */ hasAnchoringBounds()1043 public boolean hasAnchoringBounds() { 1044 return anchoringBounds; 1045 } 1046 1047 /** 1048 * Sets the anchoring of region bounds for this matcher. 1049 * 1050 * <p> Invoking this method with an argument of <tt>true</tt> will set this 1051 * matcher to use <i>anchoring</i> bounds. If the boolean 1052 * argument is <tt>false</tt>, then <i>non-anchoring</i> bounds will be 1053 * used. 1054 * 1055 * <p> Using anchoring bounds, the boundaries of this 1056 * matcher's region match anchors such as ^ and $. 1057 * 1058 * <p> Without anchoring bounds, the boundaries of this 1059 * matcher's region will not match anchors such as ^ and $. 1060 * 1061 * <p> By default, a matcher uses anchoring region boundaries. 1062 * 1063 * @param b a boolean indicating whether or not to use anchoring bounds. 1064 * @return this matcher 1065 * @see java.util.regex.Matcher#hasAnchoringBounds 1066 * @since 1.5 1067 */ useAnchoringBounds(boolean b)1068 public Matcher useAnchoringBounds(boolean b) { 1069 synchronized (this) { 1070 anchoringBounds = b; 1071 useAnchoringBoundsImpl(address, b); 1072 } 1073 return this; 1074 } 1075 1076 /** 1077 * <p>Returns the string representation of this matcher. The 1078 * string representation of a <code>Matcher</code> contains information 1079 * that may be useful for debugging. The exact format is unspecified. 1080 * 1081 * @return The string representation of this matcher 1082 * @since 1.5 1083 */ toString()1084 public String toString() { 1085 StringBuilder sb = new StringBuilder(); 1086 sb.append("java.util.regex.Matcher"); 1087 sb.append("[pattern=" + pattern()); 1088 sb.append(" region="); 1089 sb.append(regionStart() + "," + regionEnd()); 1090 sb.append(" lastmatch="); 1091 if (matchFound && (group() != null)) { 1092 sb.append(group()); 1093 } 1094 sb.append("]"); 1095 return sb.toString(); 1096 } 1097 1098 /** 1099 * <p>Returns true if the end of input was hit by the search engine in 1100 * the last match operation performed by this matcher. 1101 * 1102 * <p>When this method returns true, then it is possible that more input 1103 * would have changed the result of the last search. 1104 * 1105 * @return true iff the end of input was hit in the last match; false 1106 * otherwise 1107 * @since 1.5 1108 */ hitEnd()1109 public boolean hitEnd() { 1110 synchronized (this) { 1111 return hitEndImpl(address); 1112 } 1113 } 1114 1115 /** 1116 * <p>Returns true if more input could change a positive match into a 1117 * negative one. 1118 * 1119 * <p>If this method returns true, and a match was found, then more 1120 * input could cause the match to be lost. If this method returns false 1121 * and a match was found, then more input might change the match but the 1122 * match won't be lost. If a match was not found, then requireEnd has no 1123 * meaning. 1124 * 1125 * @return true iff more input could change a positive match into a 1126 * negative one. 1127 * @since 1.5 1128 */ requireEnd()1129 public boolean requireEnd() { 1130 synchronized (this) { 1131 return requireEndImpl(address); 1132 } 1133 } 1134 1135 /** 1136 * Returns the end index of the text. 1137 * 1138 * @return the index after the last character in the text 1139 */ getTextLength()1140 int getTextLength() { 1141 return text.length(); 1142 } 1143 1144 /** 1145 * Generates a String from this Matcher's input in the specified range. 1146 * 1147 * @param beginIndex the beginning index, inclusive 1148 * @param endIndex the ending index, exclusive 1149 * @return A String generated from this Matcher's input 1150 */ getSubSequence(int beginIndex, int endIndex)1151 CharSequence getSubSequence(int beginIndex, int endIndex) { 1152 return text.subSequence(beginIndex, endIndex); 1153 } 1154 1155 /** 1156 * Resets the Matcher. A new input sequence and a new region can be 1157 * specified. Results of a previous find get lost. The next attempt to find 1158 * an occurrence of the Pattern in the string will start at the beginning of 1159 * the region. This is the internal version of reset() to which the several 1160 * public versions delegate. 1161 * 1162 * @param input 1163 * the input sequence. 1164 * @param start 1165 * the start of the region. 1166 * @param end 1167 * the end of the region. 1168 * 1169 * @return the matcher itself. 1170 */ reset(CharSequence input, int start, int end)1171 private Matcher reset(CharSequence input, int start, int end) { 1172 if (input == null) { 1173 throw new IllegalArgumentException("input == null"); 1174 } 1175 1176 if (start < 0 || end < 0 || start > input.length() || end > input.length() || start > end) { 1177 throw new IndexOutOfBoundsException(); 1178 } 1179 1180 this.originalInput = input; 1181 this.text = input.toString(); 1182 this.from = start; 1183 this.to = end; 1184 resetForInput(); 1185 1186 matchFound = false; 1187 appendPos = 0; 1188 1189 return this; 1190 } 1191 resetForInput()1192 private void resetForInput() { 1193 synchronized (this) { 1194 setInputImpl(address, text, from, to); 1195 useAnchoringBoundsImpl(address, anchoringBounds); 1196 useTransparentBoundsImpl(address, transparentBounds); 1197 } 1198 } 1199 1200 /** 1201 * Makes sure that a successful match has been made. Is invoked internally 1202 * from various places in the class. 1203 * 1204 * @throws IllegalStateException 1205 * if no successful match has been made. 1206 */ ensureMatch()1207 private void ensureMatch() { 1208 if (!matchFound) { 1209 throw new IllegalStateException("No successful match so far"); 1210 } 1211 } 1212 getMatchedGroupIndex(String name)1213 private int getMatchedGroupIndex(String name) { 1214 ensureMatch(); 1215 int result = getMatchedGroupIndex0(parentPattern.address, name); 1216 if (result < 0) { 1217 throw new IllegalArgumentException("No capturing group in the pattern " + 1218 "with the name " + name); 1219 } 1220 return result; 1221 } 1222 getMatchedGroupIndex0(long patternAddr, String name)1223 private static native int getMatchedGroupIndex0(long patternAddr, String name); findImpl(long addr, int startIndex, int[] offsets)1224 private static native boolean findImpl(long addr, int startIndex, int[] offsets); findNextImpl(long addr, int[] offsets)1225 private static native boolean findNextImpl(long addr, int[] offsets); getNativeFinalizer()1226 private static native long getNativeFinalizer(); groupCountImpl(long addr)1227 private static native int groupCountImpl(long addr); hitEndImpl(long addr)1228 private static native boolean hitEndImpl(long addr); lookingAtImpl(long addr, int[] offsets)1229 private static native boolean lookingAtImpl(long addr, int[] offsets); matchesImpl(long addr, int[] offsets)1230 private static native boolean matchesImpl(long addr, int[] offsets); openImpl(long patternAddr)1231 private static native long openImpl(long patternAddr); requireEndImpl(long addr)1232 private static native boolean requireEndImpl(long addr); setInputImpl(long addr, String s, int start, int end)1233 private static native void setInputImpl(long addr, String s, int start, int end); useAnchoringBoundsImpl(long addr, boolean value)1234 private static native void useAnchoringBoundsImpl(long addr, boolean value); useTransparentBoundsImpl(long addr, boolean value)1235 private static native void useTransparentBoundsImpl(long addr, boolean value); 1236 1237 /** 1238 * A trivial match result implementation that's based on an array of integers 1239 * representing match offsets. The array is of the form 1240 * {@code { start1, end1, start2, end2 ....}) where each consecutive pair of elements represents 1241 * the start and end of a match respectively. 1242 */ 1243 static final class OffsetBasedMatchResult implements MatchResult { 1244 private final String input; 1245 private final int[] offsets; 1246 OffsetBasedMatchResult(String input, int[] offsets)1247 OffsetBasedMatchResult(String input, int[] offsets) { 1248 this.input = input; 1249 this.offsets = offsets.clone(); 1250 } 1251 1252 @Override start()1253 public int start() { 1254 return start(0); 1255 } 1256 1257 @Override start(int group)1258 public int start(int group) { 1259 return offsets[2 * group]; 1260 } 1261 1262 @Override end()1263 public int end() { 1264 return end(0); 1265 } 1266 1267 @Override end(int group)1268 public int end(int group) { 1269 return offsets[2 * group + 1]; 1270 } 1271 1272 @Override group()1273 public String group() { 1274 return group(0); 1275 } 1276 1277 @Override group(int group)1278 public String group(int group) { 1279 final int start = start(group); 1280 final int end = end(group); 1281 if (start == -1 || end == -1) { 1282 return null; 1283 } 1284 1285 return input.substring(start, end); 1286 } 1287 1288 @Override groupCount()1289 public int groupCount() { 1290 return (offsets.length / 2) - 1; 1291 } 1292 } 1293 } 1294