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