Matcher.java 20.2 KB
Newer Older
Tom Tromey committed
1
/* Matcher.java -- Instance of a regular expression applied to a char sequence.
2
   Copyright (C) 2002, 2004, 2006 Free Software Foundation, Inc.
Tom Tromey committed
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40

This file is part of GNU Classpath.

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */


package java.util.regex;

41 42
import gnu.java.lang.CPStringBuilder;

43 44 45
import gnu.java.util.regex.CharIndexed;
import gnu.java.util.regex.RE;
import gnu.java.util.regex.REMatch;
Tom Tromey committed
46 47 48 49 50 51

/**
 * Instance of a regular expression applied to a char sequence.
 *
 * @since 1.4
 */
52
public final class Matcher implements MatchResult
Tom Tromey committed
53 54 55
{
  private Pattern pattern;
  private CharSequence input;
56 57 58 59
  // We use CharIndexed as an input object to the getMatch method in order
  // that /\G/ (the end of the previous match) may work.  The information
  // of the previous match is stored in the CharIndexed object.
  private CharIndexed inputCharIndexed;
Tom Tromey committed
60 61 62 63
  private int position;
  private int appendPosition;
  private REMatch match;

64 65 66 67 68 69 70 71 72
  /**
   * The start of the region of the input on which to match.
   */
  private int regionStart;

  /**
   * The end of the region of the input on which to match.
   */
  private int regionEnd;
73

74
  /**
75
   * True if the match process should look beyond the
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
   * region marked by regionStart to regionEnd when
   * performing lookAhead, lookBehind and boundary
   * matching.
   */
  private boolean transparentBounds;

  /**
   * The flags that affect the anchoring bounds.
   * If {@link #hasAnchoringBounds()} is {@code true},
   * the match process will honour the
   * anchoring bounds: ^, \A, \Z, \z and $.  If
   * {@link #hasAnchoringBounds()} is {@code false},
   * the anchors are ignored and appropriate flags,
   * stored in this variable, are used to provide this
   * behaviour.
   */
  private int anchoringBounds;

Tom Tromey committed
94 95 96 97
  Matcher(Pattern pattern, CharSequence input)
  {
    this.pattern = pattern;
    this.input = input;
98
    this.inputCharIndexed = RE.makeCharIndexed(input, 0);
99 100 101 102
    regionStart = 0;
    regionEnd = input.length();
    transparentBounds = false;
    anchoringBounds = 0;
Tom Tromey committed
103
  }
104

Tom Tromey committed
105
  /**
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
   * Changes the pattern used by the {@link Matcher} to
   * the one specified.  Existing match information is lost,
   * but the input and the matcher's position within it is
   * retained.
   *
   * @param newPattern the new pattern to use.
   * @return this matcher.
   * @throws IllegalArgumentException if {@code newPattern} is
   *                                  {@code null}.
   * @since 1.5
   */
  public Matcher usePattern(Pattern newPattern)
  {
    if (newPattern == null)
      throw new IllegalArgumentException("The new pattern was null.");
    pattern = newPattern;
    match = null;

    return this;
  }

  /**
Tom Tromey committed
128 129 130 131 132 133 134 135 136 137 138 139 140
   * @param sb The target string buffer
   * @param replacement The replacement string
   *
   * @exception IllegalStateException If no match has yet been attempted,
   * or if the previous match operation failed
   * @exception IndexOutOfBoundsException If the replacement string refers
   * to a capturing group that does not exist in the pattern
   */
  public Matcher appendReplacement (StringBuffer sb, String replacement)
    throws IllegalStateException
  {
    assertMatchOp();
    sb.append(input.subSequence(appendPosition,
141
                                match.getStartIndex()).toString());
142
    sb.append(RE.getReplacement(replacement, match,
143
        RE.REG_REPLACE_USE_BACKSLASHESCAPE));
Tom Tromey committed
144 145 146 147 148 149 150 151 152 153 154 155
    appendPosition = match.getEndIndex();
    return this;
  }

  /**
   * @param sb The target string buffer
   */
  public StringBuffer appendTail (StringBuffer sb)
  {
    sb.append(input.subSequence(appendPosition, input.length()).toString());
    return sb;
  }
156

Tom Tromey committed
157 158 159 160 161 162 163 164 165 166
  /**
   * @exception IllegalStateException If no match has yet been attempted,
   * or if the previous match operation failed
   */
  public int end ()
    throws IllegalStateException
  {
    assertMatchOp();
    return match.getEndIndex();
  }
167

Tom Tromey committed
168 169 170 171 172 173 174 175 176 177 178 179 180 181
  /**
   * @param group The index of a capturing group in this matcher's pattern
   *
   * @exception IllegalStateException If no match has yet been attempted,
   * or if the previous match operation failed
   * @exception IndexOutOfBoundsException If the replacement string refers
   * to a capturing group that does not exist in the pattern
   */
  public int end (int group)
    throws IllegalStateException
  {
    assertMatchOp();
    return match.getEndIndex(group);
  }
182

Tom Tromey committed
183 184 185
  public boolean find ()
  {
    boolean first = (match == null);
186 187 188 189
    if (transparentBounds || (regionStart == 0 && regionEnd == input.length()))
      match = pattern.getRE().getMatch(inputCharIndexed, position, anchoringBounds);
    else
      match = pattern.getRE().getMatch(input.subSequence(regionStart, regionEnd),
190
                                       position, anchoringBounds);
Tom Tromey committed
191 192
    if (match != null)
      {
193
        int endIndex = match.getEndIndex();
194 195 196 197 198 199
        // Is the match within input limits?
        if (endIndex > input.length())
          {
            match = null;
            return false;
          }
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
        // Are we stuck at the same position?
        if (!first && endIndex == position)
          {
            match = null;
            // Not at the end of the input yet?
            if (position < input.length() - 1)
              {
                position++;
                return find(position);
              }
            else
              return false;
          }
        position = endIndex;
        return true;
Tom Tromey committed
215 216
      }
    return false;
217
  }
Tom Tromey committed
218 219 220 221 222 223 224 225 226

  /**
   * @param start The index to start the new pattern matching
   *
   * @exception IndexOutOfBoundsException If the replacement string refers
   * to a capturing group that does not exist in the pattern
   */
  public boolean find (int start)
  {
227 228 229 230
    if (transparentBounds || (regionStart == 0 && regionEnd == input.length()))
      match = pattern.getRE().getMatch(inputCharIndexed, start, anchoringBounds);
    else
      match = pattern.getRE().getMatch(input.subSequence(regionStart, regionEnd),
231
                                       start, anchoringBounds);
Tom Tromey committed
232 233
    if (match != null)
      {
234 235
        position = match.getEndIndex();
        return true;
Tom Tromey committed
236 237 238
      }
    return false;
  }
239

Tom Tromey committed
240 241 242 243 244 245 246 247 248
  /**
   * @exception IllegalStateException If no match has yet been attempted,
   * or if the previous match operation failed
   */
  public String group ()
  {
    assertMatchOp();
    return match.toString();
  }
249

Tom Tromey committed
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
  /**
   * @param group The index of a capturing group in this matcher's pattern
   *
   * @exception IllegalStateException If no match has yet been attempted,
   * or if the previous match operation failed
   * @exception IndexOutOfBoundsException If the replacement string refers
   * to a capturing group that does not exist in the pattern
   */
  public String group (int group)
    throws IllegalStateException
  {
    assertMatchOp();
    return match.toString(group);
  }

  /**
   * @param replacement The replacement string
   */
  public String replaceFirst (String replacement)
  {
    reset();
    // Semantics might not quite match
272
    return pattern.getRE().substitute(input, replacement, position,
273
        RE.REG_REPLACE_USE_BACKSLASHESCAPE);
Tom Tromey committed
274 275 276 277 278 279 280 281
  }

  /**
   * @param replacement The replacement string
   */
  public String replaceAll (String replacement)
  {
    reset();
282
    return pattern.getRE().substituteAll(input, replacement, position,
283
        RE.REG_REPLACE_USE_BACKSLASHESCAPE);
Tom Tromey committed
284
  }
285

Tom Tromey committed
286 287 288 289
  public int groupCount ()
  {
    return pattern.getRE().getNumSubs();
  }
290

Tom Tromey committed
291 292
  public boolean lookingAt ()
  {
293 294
    if (transparentBounds || (regionStart == 0 && regionEnd == input.length()))
      match = pattern.getRE().getMatch(inputCharIndexed, regionStart,
295
                                       anchoringBounds|RE.REG_FIX_STARTING_POSITION|RE.REG_ANCHORINDEX);
296 297
    else
      match = pattern.getRE().getMatch(input.subSequence(regionStart, regionEnd), 0,
298
                                       anchoringBounds|RE.REG_FIX_STARTING_POSITION);
Tom Tromey committed
299 300
    if (match != null)
      {
301 302 303 304 305 306
        if (match.getStartIndex() == 0)
          {
            position = match.getEndIndex();
            return true;
          }
        match = null;
Tom Tromey committed
307 308 309
      }
    return false;
  }
310

Tom Tromey committed
311
  /**
312
   * Attempts to match the entire input sequence against the pattern.
Tom Tromey committed
313 314 315 316
   *
   * If the match succeeds then more information can be obtained via the
   * start, end, and group methods.
   *
317 318 319
   * @see #start()
   * @see #end()
   * @see #group()
Tom Tromey committed
320 321 322
   */
  public boolean matches ()
  {
323 324
    if (transparentBounds || (regionStart == 0 && regionEnd == input.length()))
      match = pattern.getRE().getMatch(inputCharIndexed, regionStart,
325
                                       anchoringBounds|RE.REG_TRY_ENTIRE_MATCH|RE.REG_FIX_STARTING_POSITION|RE.REG_ANCHORINDEX);
326 327
    else
      match = pattern.getRE().getMatch(input.subSequence(regionStart, regionEnd), 0,
328
                                       anchoringBounds|RE.REG_TRY_ENTIRE_MATCH|RE.REG_FIX_STARTING_POSITION);
329
    if (match != null)
Tom Tromey committed
330
      {
331 332 333 334 335 336 337
        if (match.getStartIndex() == 0)
          {
            position = match.getEndIndex();
            if (position == input.length())
                return true;
          }
        match = null;
Tom Tromey committed
338 339 340
      }
    return false;
  }
341

Tom Tromey committed
342 343 344 345 346 347 348
  /**
   * Returns the Pattern that is interpreted by this Matcher
   */
  public Pattern pattern ()
  {
    return pattern;
  }
349

350 351 352 353 354 355 356 357 358 359 360 361
  /**
   * Resets the internal state of the matcher, including
   * resetting the region to its default state of encompassing
   * the whole input.  The state of {@link #hasTransparentBounds()}
   * and {@link #hasAnchoringBounds()} are unaffected.
   *
   * @return a reference to this matcher.
   * @see #regionStart()
   * @see #regionEnd()
   * @see #hasTransparentBounds()
   * @see #hasAnchoringBounds()
   */
Tom Tromey committed
362 363 364 365
  public Matcher reset ()
  {
    position = 0;
    match = null;
366 367 368
    regionStart = 0;
    regionEnd = input.length();
    appendPosition = 0;
Tom Tromey committed
369 370
    return this;
  }
371

Tom Tromey committed
372
  /**
373 374 375 376 377 378 379 380 381 382 383
   * Resets the internal state of the matcher, including
   * resetting the region to its default state of encompassing
   * the whole input.  The state of {@link #hasTransparentBounds()}
   * and {@link #hasAnchoringBounds()} are unaffected.
   *
   * @param input The new input character sequence.
   * @return a reference to this matcher.
   * @see #regionStart()
   * @see #regionEnd()
   * @see #hasTransparentBounds()
   * @see #hasAnchoringBounds()
Tom Tromey committed
384 385 386 387
   */
  public Matcher reset (CharSequence input)
  {
    this.input = input;
388
    this.inputCharIndexed = RE.makeCharIndexed(input, 0);
Tom Tromey committed
389 390
    return reset();
  }
391

Tom Tromey committed
392
  /**
393
   * @return the index of a capturing group in this matcher's pattern
Tom Tromey committed
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
   *
   * @exception IllegalStateException If no match has yet been attempted,
   * or if the previous match operation failed
   */
  public int start ()
    throws IllegalStateException
  {
    assertMatchOp();
    return match.getStartIndex();
  }

  /**
   * @param group The index of a capturing group in this matcher's pattern
   *
   * @exception IllegalStateException If no match has yet been attempted,
   * or if the previous match operation failed
   * @exception IndexOutOfBoundsException If the replacement string refers
   * to a capturing group that does not exist in the pattern
   */
  public int start (int group)
    throws IllegalStateException
  {
    assertMatchOp();
    return match.getStartIndex(group);
  }

420 421
  /**
   * @return True if and only if the matcher hit the end of input.
422
   * @since 1.5
423 424 425 426 427 428 429 430 431 432 433
   */
  public boolean hitEnd()
  {
    return inputCharIndexed.hitEnd();
  }

  /**
   * @return A string expression of this matcher.
   */
  public String toString()
  {
434
    CPStringBuilder sb = new CPStringBuilder();
435 436
    sb.append(this.getClass().getName())
      .append("[pattern=").append(pattern.pattern())
437 438 439
      .append(" region=").append(regionStart).append(",").append(regionEnd)
      .append(" anchoringBounds=").append(anchoringBounds == 0)
      .append(" transparentBounds=").append(transparentBounds)
440 441 442 443 444
      .append(" lastmatch=").append(match == null ? "" : match.toString())
      .append("]");
    return sb.toString();
  }

Tom Tromey committed
445 446 447 448
  private void assertMatchOp()
  {
    if (match == null) throw new IllegalStateException();
  }
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523

  /**
   * <p>
   * Defines the region of the input on which to match.
   * By default, the {@link Matcher} attempts to match
   * the whole string (from 0 to the length of the input),
   * but a region between {@code start} (inclusive) and
   * {@code end} (exclusive) on which to match may instead
   * be defined using this method.
   * </p>
   * <p>
   * The behaviour of region matching is further affected
   * by the use of transparent or opaque bounds (see
   * {@link #useTransparentBounds(boolean)}) and whether or not
   * anchors ({@code ^} and {@code $}) are in use
   * (see {@link #useAnchoringBounds(boolean)}).  With transparent
   * bounds, the matcher is aware of input outside the bounds
   * set by this method, whereas, with opaque bounds (the default)
   * only the input within the bounds is used.  The use of
   * anchors are affected by this setting; with transparent
   * bounds, anchors will match the beginning of the real input,
   * while with opaque bounds they match the beginning of the
   * region.  {@link #useAnchoringBounds(boolean)} can be used
   * to turn on or off the matching of anchors.
   * </p>
   *
   * @param start the start of the region (inclusive).
   * @param end the end of the region (exclusive).
   * @return a reference to this matcher.
   * @throws IndexOutOfBoundsException if either {@code start} or
   *                                   {@code end} are less than zero,
   *                                   if either {@code start} or
   *                                   {@code end} are greater than the
   *                                   length of the input, or if
   *                                   {@code start} is greater than
   *                                   {@code end}.
   * @see #regionStart()
   * @see #regionEnd()
   * @see #hasTransparentBounds()
   * @see #useTransparentBounds(boolean)
   * @see #hasAnchoringBounds()
   * @see #useAnchoringBounds(boolean)
   * @since 1.5
   */
  public Matcher region(int start, int end)
  {
    int length = input.length();
    if (start < 0)
      throw new IndexOutOfBoundsException("The start position was less than zero.");
    if (start >= length)
      throw new IndexOutOfBoundsException("The start position is after the end of the input.");
    if (end < 0)
      throw new IndexOutOfBoundsException("The end position was less than zero.");
    if (end > length)
      throw new IndexOutOfBoundsException("The end position is after the end of the input.");
    if (start > end)
      throw new IndexOutOfBoundsException("The start position is after the end position.");
    reset();
    regionStart = start;
    regionEnd = end;
    return this;
  }

  /**
   * The start of the region on which to perform matches (inclusive).
   *
   * @return the start index of the region.
   * @see #region(int,int)
   * #see #regionEnd()
   * @since 1.5
   */
  public int regionStart()
  {
    return regionStart;
  }
524

525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
  /**
   * The end of the region on which to perform matches (exclusive).
   *
   * @return the end index of the region.
   * @see #region(int,int)
   * @see #regionStart()
   * @since 1.5
   */
  public int regionEnd()
  {
    return regionEnd;
  }

  /**
   * Returns true if the bounds of the region marked by
   * {@link #regionStart()} and {@link #regionEnd()} are
   * transparent.  When these bounds are transparent, the
   * matching process can look beyond them to perform
   * lookahead, lookbehind and boundary matching operations.
   * By default, the bounds are opaque.
   *
   * @return true if the bounds of the matching region are
   *         transparent.
   * @see #useTransparentBounds(boolean)
   * @see #region(int,int)
   * @see #regionStart()
   * @see #regionEnd()
   * @since 1.5
   */
  public boolean hasTransparentBounds()
  {
    return transparentBounds;
  }

  /**
   * Sets the transparency of the bounds of the region
   * marked by {@link #regionStart()} and {@link #regionEnd()}.
   * A value of {@code true} makes the bounds transparent,
   * so the matcher can see beyond them to perform lookahead,
   * lookbehind and boundary matching operations.  A value
   * of {@code false} (the default) makes the bounds opaque,
   * restricting the match to the input region denoted
   * by {@link #regionStart()} and {@link #regionEnd()}.
   *
   * @param transparent true if the bounds should be transparent.
   * @return a reference to this matcher.
   * @see #hasTransparentBounds()
   * @see #region(int,int)
   * @see #regionStart()
   * @see #regionEnd()
   * @since 1.5
   */
  public Matcher useTransparentBounds(boolean transparent)
  {
    transparentBounds = transparent;
    return this;
  }

  /**
   * Returns true if the matcher will honour the use of
   * the anchoring bounds: {@code ^}, {@code \A}, {@code \Z},
   * {@code \z} and {@code $}.  By default, the anchors
   * are used.  Note that the effect of the anchors is
   * also affected by {@link #hasTransparentBounds()}.
   *
   * @return true if the matcher will attempt to match
   *         the anchoring bounds.
   * @see #useAnchoringBounds(boolean)
   * @see #hasTransparentBounds()
   * @since 1.5
   */
  public boolean hasAnchoringBounds()
  {
    return anchoringBounds == 0;
  }

  /**
   * Enables or disables the use of the anchoring bounds:
   * {@code ^}, {@code \A}, {@code \Z}, {@code \z} and
   * {@code $}. By default, their use is enabled.  When
   * disabled, the matcher will not attempt to match
   * the anchors.
   *
   * @param useAnchors true if anchoring bounds should be used.
   * @return a reference to this matcher.
   * @since 1.5
   * @see #hasAnchoringBounds()
   */
  public Matcher useAnchoringBounds(boolean useAnchors)
  {
    if (useAnchors)
      anchoringBounds = 0;
    else
      anchoringBounds = RE.REG_NOTBOL|RE.REG_NOTEOL;
    return this;
  }

  /**
   * Returns a read-only snapshot of the current state of
   * the {@link Matcher} as a {@link MatchResult}.  Any
   * subsequent changes to this instance are not reflected
   * in the returned {@link MatchResult}.
   *
   * @return a {@link MatchResult} instance representing the
   *         current state of the {@link Matcher}.
   */
  public MatchResult toMatchResult()
  {
    Matcher snapshot = new Matcher(pattern, input);
634 635
    if (match != null)
      snapshot.match = (REMatch) match.clone();
636 637 638
    return snapshot;
  }

639 640 641 642 643 644
  /**
   * Returns a literalized string of s where characters {@code $} and {@code
   * \\} are escaped.
   *
   * @param s the string to literalize.
   * @return the literalized string.
645
   * @since 1.5
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
   */
  public static String quoteReplacement(String s)
  {
    if (s == null)
      throw new NullPointerException();
    CPStringBuilder sb = new CPStringBuilder();
    for (int i = 0; i < s.length(); i++)
    {
      char ch = s.charAt(i);
      if (ch == '$' || ch == '\\')
        sb.append('\\');
      sb.append(ch);
    }
    return sb.toString();
  }

Tom Tromey committed
662
}