0N/A/*
2362N/A * Copyright (c) 1999, 2009, Oracle and/or its affiliates. All rights reserved.
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
2362N/A * published by the Free Software Foundation. Oracle designates this
0N/A * particular file as subject to the "Classpath" exception as provided
2362N/A * by Oracle in the LICENSE file that accompanied this code.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * questions.
0N/A */
0N/A
0N/Apackage java.util.regex;
0N/A
0N/A
0N/A/**
0N/A * An engine that performs match operations on a {@link java.lang.CharSequence
0N/A * </code>character sequence<code>} by interpreting a {@link Pattern}.
0N/A *
0N/A * <p> A matcher is created from a pattern by invoking the pattern's {@link
0N/A * Pattern#matcher matcher} method. Once created, a matcher can be used to
0N/A * perform three different kinds of match operations:
0N/A *
0N/A * <ul>
0N/A *
0N/A * <li><p> The {@link #matches matches} method attempts to match the entire
0N/A * input sequence against the pattern. </p></li>
0N/A *
0N/A * <li><p> The {@link #lookingAt lookingAt} method attempts to match the
0N/A * input sequence, starting at the beginning, against the pattern. </p></li>
0N/A *
0N/A * <li><p> The {@link #find find} method scans the input sequence looking for
0N/A * the next subsequence that matches the pattern. </p></li>
0N/A *
0N/A * </ul>
0N/A *
0N/A * <p> Each of these methods returns a boolean indicating success or failure.
0N/A * More information about a successful match can be obtained by querying the
0N/A * state of the matcher.
0N/A *
0N/A * <p> A matcher finds matches in a subset of its input called the
0N/A * <i>region</i>. By default, the region contains all of the matcher's input.
0N/A * The region can be modified via the{@link #region region} method and queried
0N/A * via the {@link #regionStart regionStart} and {@link #regionEnd regionEnd}
0N/A * methods. The way that the region boundaries interact with some pattern
0N/A * constructs can be changed. See {@link #useAnchoringBounds
0N/A * useAnchoringBounds} and {@link #useTransparentBounds useTransparentBounds}
0N/A * for more details.
0N/A *
0N/A * <p> This class also defines methods for replacing matched subsequences with
0N/A * new strings whose contents can, if desired, be computed from the match
0N/A * result. The {@link #appendReplacement appendReplacement} and {@link
0N/A * #appendTail appendTail} methods can be used in tandem in order to collect
0N/A * the result into an existing string buffer, or the more convenient {@link
0N/A * #replaceAll replaceAll} method can be used to create a string in which every
0N/A * matching subsequence in the input sequence is replaced.
0N/A *
0N/A * <p> The explicit state of a matcher includes the start and end indices of
0N/A * the most recent successful match. It also includes the start and end
0N/A * indices of the input subsequence captured by each <a
0N/A * href="Pattern.html#cg">capturing group</a> in the pattern as well as a total
0N/A * count of such subsequences. As a convenience, methods are also provided for
0N/A * returning these captured subsequences in string form.
0N/A *
0N/A * <p> The explicit state of a matcher is initially undefined; attempting to
0N/A * query any part of it before a successful match will cause an {@link
0N/A * IllegalStateException} to be thrown. The explicit state of a matcher is
0N/A * recomputed by every match operation.
0N/A *
0N/A * <p> The implicit state of a matcher includes the input character sequence as
0N/A * well as the <i>append position</i>, which is initially zero and is updated
0N/A * by the {@link #appendReplacement appendReplacement} method.
0N/A *
0N/A * <p> A matcher may be reset explicitly by invoking its {@link #reset()}
0N/A * method or, if a new input sequence is desired, its {@link
0N/A * #reset(java.lang.CharSequence) reset(CharSequence)} method. Resetting a
0N/A * matcher discards its explicit state information and sets the append position
0N/A * to zero.
0N/A *
0N/A * <p> Instances of this class are not safe for use by multiple concurrent
0N/A * threads. </p>
0N/A *
0N/A *
0N/A * @author Mike McCloskey
0N/A * @author Mark Reinhold
0N/A * @author JSR-51 Expert Group
0N/A * @since 1.4
0N/A * @spec JSR-51
0N/A */
0N/A
0N/Apublic final class Matcher implements MatchResult {
0N/A
0N/A /**
0N/A * The Pattern object that created this Matcher.
0N/A */
0N/A Pattern parentPattern;
0N/A
0N/A /**
0N/A * The storage used by groups. They may contain invalid values if
0N/A * a group was skipped during the matching.
0N/A */
0N/A int[] groups;
0N/A
0N/A /**
0N/A * The range within the sequence that is to be matched. Anchors
0N/A * will match at these "hard" boundaries. Changing the region
0N/A * changes these values.
0N/A */
0N/A int from, to;
0N/A
0N/A /**
0N/A * Lookbehind uses this value to ensure that the subexpression
0N/A * match ends at the point where the lookbehind was encountered.
0N/A */
0N/A int lookbehindTo;
0N/A
0N/A /**
0N/A * The original string being matched.
0N/A */
0N/A CharSequence text;
0N/A
0N/A /**
0N/A * Matcher state used by the last node. NOANCHOR is used when a
0N/A * match does not have to consume all of the input. ENDANCHOR is
0N/A * the mode used for matching all the input.
0N/A */
0N/A static final int ENDANCHOR = 1;
0N/A static final int NOANCHOR = 0;
0N/A int acceptMode = NOANCHOR;
0N/A
0N/A /**
0N/A * The range of string that last matched the pattern. If the last
0N/A * match failed then first is -1; last initially holds 0 then it
0N/A * holds the index of the end of the last match (which is where the
0N/A * next search starts).
0N/A */
0N/A int first = -1, last = 0;
0N/A
0N/A /**
0N/A * The end index of what matched in the last match operation.
0N/A */
0N/A int oldLast = -1;
0N/A
0N/A /**
0N/A * The index of the last position appended in a substitution.
0N/A */
0N/A int lastAppendPosition = 0;
0N/A
0N/A /**
0N/A * Storage used by nodes to tell what repetition they are on in
0N/A * a pattern, and where groups begin. The nodes themselves are stateless,
0N/A * so they rely on this field to hold state during a match.
0N/A */
0N/A int[] locals;
0N/A
0N/A /**
0N/A * Boolean indicating whether or not more input could change
0N/A * the results of the last match.
0N/A *
0N/A * If hitEnd is true, and a match was found, then more input
0N/A * might cause a different match to be found.
0N/A * If hitEnd is true and a match was not found, then more
0N/A * input could cause a match to be found.
0N/A * If hitEnd is false and a match was found, then more input
0N/A * will not change the match.
0N/A * If hitEnd is false and a match was not found, then more
0N/A * input will not cause a match to be found.
0N/A */
0N/A boolean hitEnd;
0N/A
0N/A /**
0N/A * Boolean indicating whether or not more input could change
0N/A * a positive match into a negative one.
0N/A *
0N/A * If requireEnd is true, and a match was found, then more
0N/A * input could cause the match to be lost.
0N/A * If requireEnd is false and a match was found, then more
0N/A * input might change the match but the match won't be lost.
0N/A * If a match was not found, then requireEnd has no meaning.
0N/A */
0N/A boolean requireEnd;
0N/A
0N/A /**
0N/A * If transparentBounds is true then the boundaries of this
0N/A * matcher's region are transparent to lookahead, lookbehind,
0N/A * and boundary matching constructs that try to see beyond them.
0N/A */
0N/A boolean transparentBounds = false;
0N/A
0N/A /**
0N/A * If anchoringBounds is true then the boundaries of this
0N/A * matcher's region match anchors such as ^ and $.
0N/A */
0N/A boolean anchoringBounds = true;
0N/A
0N/A /**
0N/A * No default constructor.
0N/A */
0N/A Matcher() {
0N/A }
0N/A
0N/A /**
0N/A * All matchers have the state used by Pattern during a match.
0N/A */
0N/A Matcher(Pattern parent, CharSequence text) {
0N/A this.parentPattern = parent;
0N/A this.text = text;
0N/A
0N/A // Allocate state storage
0N/A int parentGroupCount = Math.max(parent.capturingGroupCount, 10);
0N/A groups = new int[parentGroupCount * 2];
0N/A locals = new int[parent.localCount];
0N/A
0N/A // Put fields into initial states
0N/A reset();
0N/A }
0N/A
0N/A /**
0N/A * Returns the pattern that is interpreted by this matcher.
0N/A *
0N/A * @return The pattern for which this matcher was created
0N/A */
0N/A public Pattern pattern() {
0N/A return parentPattern;
0N/A }
0N/A
0N/A /**
0N/A * Returns the match state of this matcher as a {@link MatchResult}.
0N/A * The result is unaffected by subsequent operations performed upon this
0N/A * matcher.
0N/A *
0N/A * @return a <code>MatchResult</code> with the state of this matcher
0N/A * @since 1.5
0N/A */
0N/A public MatchResult toMatchResult() {
0N/A Matcher result = new Matcher(this.parentPattern, text.toString());
0N/A result.first = this.first;
0N/A result.last = this.last;
28N/A result.groups = this.groups.clone();
0N/A return result;
0N/A }
0N/A
0N/A /**
0N/A * Changes the <tt>Pattern</tt> that this <tt>Matcher</tt> uses to
0N/A * find matches with.
0N/A *
0N/A * <p> This method causes this matcher to lose information
0N/A * about the groups of the last match that occurred. The
0N/A * matcher's position in the input is maintained and its
0N/A * last append position is unaffected.</p>
0N/A *
0N/A * @param newPattern
0N/A * The new pattern used by this matcher
0N/A * @return This matcher
0N/A * @throws IllegalArgumentException
0N/A * If newPattern is <tt>null</tt>
0N/A * @since 1.5
0N/A */
0N/A public Matcher usePattern(Pattern newPattern) {
0N/A if (newPattern == null)
0N/A throw new IllegalArgumentException("Pattern cannot be null");
0N/A parentPattern = newPattern;
0N/A
0N/A // Reallocate state storage
0N/A int parentGroupCount = Math.max(newPattern.capturingGroupCount, 10);
0N/A groups = new int[parentGroupCount * 2];
0N/A locals = new int[newPattern.localCount];
0N/A for (int i = 0; i < groups.length; i++)
0N/A groups[i] = -1;
0N/A for (int i = 0; i < locals.length; i++)
0N/A locals[i] = -1;
0N/A return this;
0N/A }
0N/A
0N/A /**
0N/A * Resets this matcher.
0N/A *
0N/A * <p> Resetting a matcher discards all of its explicit state information
0N/A * and sets its append position to zero. The matcher's region is set to the
0N/A * default region, which is its entire character sequence. The anchoring
0N/A * and transparency of this matcher's region boundaries are unaffected.
0N/A *
0N/A * @return This matcher
0N/A */
0N/A public Matcher reset() {
0N/A first = -1;
0N/A last = 0;
0N/A oldLast = -1;
0N/A for(int i=0; i<groups.length; i++)
0N/A groups[i] = -1;
0N/A for(int i=0; i<locals.length; i++)
0N/A locals[i] = -1;
0N/A lastAppendPosition = 0;
0N/A from = 0;
0N/A to = getTextLength();
0N/A return this;
0N/A }
0N/A
0N/A /**
0N/A * Resets this matcher with a new input sequence.
0N/A *
0N/A * <p> Resetting a matcher discards all of its explicit state information
0N/A * and sets its append position to zero. The matcher's region is set to
0N/A * the default region, which is its entire character sequence. The
0N/A * anchoring and transparency of this matcher's region boundaries are
0N/A * unaffected.
0N/A *
0N/A * @param input
0N/A * The new input character sequence
0N/A *
0N/A * @return This matcher
0N/A */
0N/A public Matcher reset(CharSequence input) {
0N/A text = input;
0N/A return reset();
0N/A }
0N/A
0N/A /**
0N/A * Returns the start index of the previous match. </p>
0N/A *
0N/A * @return The index of the first character matched
0N/A *
0N/A * @throws IllegalStateException
0N/A * If no match has yet been attempted,
0N/A * or if the previous match operation failed
0N/A */
0N/A public int start() {
0N/A if (first < 0)
0N/A throw new IllegalStateException("No match available");
0N/A return first;
0N/A }
0N/A
0N/A /**
0N/A * Returns the start index of the subsequence captured by the given group
0N/A * during the previous match operation.
0N/A *
0N/A * <p> <a href="Pattern.html#cg">Capturing groups</a> are indexed from left
0N/A * to right, starting at one. Group zero denotes the entire pattern, so
0N/A * the expression <i>m.</i><tt>start(0)</tt> is equivalent to
0N/A * <i>m.</i><tt>start()</tt>. </p>
0N/A *
0N/A * @param group
0N/A * The index of a capturing group in this matcher's pattern
0N/A *
0N/A * @return The index of the first character captured by the group,
0N/A * or <tt>-1</tt> if the match was successful but the group
0N/A * itself did not match anything
0N/A *
0N/A * @throws IllegalStateException
0N/A * If no match has yet been attempted,
0N/A * or if the previous match operation failed
0N/A *
0N/A * @throws IndexOutOfBoundsException
0N/A * If there is no capturing group in the pattern
0N/A * with the given index
0N/A */
0N/A public int start(int group) {
0N/A if (first < 0)
0N/A throw new IllegalStateException("No match available");
0N/A if (group > groupCount())
0N/A throw new IndexOutOfBoundsException("No group " + group);
0N/A return groups[group * 2];
0N/A }
0N/A
0N/A /**
0N/A * Returns the offset after the last character matched. </p>
0N/A *
0N/A * @return The offset after the last character matched
0N/A *
0N/A * @throws IllegalStateException
0N/A * If no match has yet been attempted,
0N/A * or if the previous match operation failed
0N/A */
0N/A public int end() {
0N/A if (first < 0)
0N/A throw new IllegalStateException("No match available");
0N/A return last;
0N/A }
0N/A
0N/A /**
0N/A * Returns the offset after the last character of the subsequence
0N/A * captured by the given group during the previous match operation.
0N/A *
0N/A * <p> <a href="Pattern.html#cg">Capturing groups</a> are indexed from left
0N/A * to right, starting at one. Group zero denotes the entire pattern, so
0N/A * the expression <i>m.</i><tt>end(0)</tt> is equivalent to
0N/A * <i>m.</i><tt>end()</tt>. </p>
0N/A *
0N/A * @param group
0N/A * The index of a capturing group in this matcher's pattern
0N/A *
0N/A * @return The offset after the last character captured by the group,
0N/A * or <tt>-1</tt> if the match was successful
0N/A * but the group itself did not match anything
0N/A *
0N/A * @throws IllegalStateException
0N/A * If no match has yet been attempted,
0N/A * or if the previous match operation failed
0N/A *
0N/A * @throws IndexOutOfBoundsException
0N/A * If there is no capturing group in the pattern
0N/A * with the given index
0N/A */
0N/A public int end(int group) {
0N/A if (first < 0)
0N/A throw new IllegalStateException("No match available");
0N/A if (group > groupCount())
0N/A throw new IndexOutOfBoundsException("No group " + group);
0N/A return groups[group * 2 + 1];
0N/A }
0N/A
0N/A /**
0N/A * Returns the input subsequence matched by the previous match.
0N/A *
0N/A * <p> For a matcher <i>m</i> with input sequence <i>s</i>,
0N/A * the expressions <i>m.</i><tt>group()</tt> and
0N/A * <i>s.</i><tt>substring(</tt><i>m.</i><tt>start(),</tt>&nbsp;<i>m.</i><tt>end())</tt>
0N/A * are equivalent. </p>
0N/A *
0N/A * <p> Note that some patterns, for example <tt>a*</tt>, match the empty
0N/A * string. This method will return the empty string when the pattern
0N/A * successfully matches the empty string in the input. </p>
0N/A *
0N/A * @return The (possibly empty) subsequence matched by the previous match,
0N/A * in string form
0N/A *
0N/A * @throws IllegalStateException
0N/A * If no match has yet been attempted,
0N/A * or if the previous match operation failed
0N/A */
0N/A public String group() {
0N/A return group(0);
0N/A }
0N/A
0N/A /**
0N/A * Returns the input subsequence captured by the given group during the
0N/A * previous match operation.
0N/A *
0N/A * <p> For a matcher <i>m</i>, input sequence <i>s</i>, and group index
0N/A * <i>g</i>, the expressions <i>m.</i><tt>group(</tt><i>g</i><tt>)</tt> and
0N/A * <i>s.</i><tt>substring(</tt><i>m.</i><tt>start(</tt><i>g</i><tt>),</tt>&nbsp;<i>m.</i><tt>end(</tt><i>g</i><tt>))</tt>
0N/A * are equivalent. </p>
0N/A *
0N/A * <p> <a href="Pattern.html#cg">Capturing groups</a> are indexed from left
0N/A * to right, starting at one. Group zero denotes the entire pattern, so
0N/A * the expression <tt>m.group(0)</tt> is equivalent to <tt>m.group()</tt>.
0N/A * </p>
0N/A *
0N/A * <p> If the match was successful but the group specified failed to match
0N/A * any part of the input sequence, then <tt>null</tt> is returned. Note
0N/A * that some groups, for example <tt>(a*)</tt>, match the empty string.
0N/A * This method will return the empty string when such a group successfully
0N/A * matches the empty string in the input. </p>
0N/A *
0N/A * @param group
0N/A * The index of a capturing group in this matcher's pattern
0N/A *
0N/A * @return The (possibly empty) subsequence captured by the group
0N/A * during the previous match, or <tt>null</tt> if the group
0N/A * failed to match part of the input
0N/A *
0N/A * @throws IllegalStateException
0N/A * If no match has yet been attempted,
0N/A * or if the previous match operation failed
0N/A *
0N/A * @throws IndexOutOfBoundsException
0N/A * If there is no capturing group in the pattern
0N/A * with the given index
0N/A */
0N/A public String group(int group) {
0N/A if (first < 0)
0N/A throw new IllegalStateException("No match found");
0N/A if (group < 0 || group > groupCount())
0N/A throw new IndexOutOfBoundsException("No group " + group);
0N/A if ((groups[group*2] == -1) || (groups[group*2+1] == -1))
0N/A return null;
0N/A return getSubSequence(groups[group * 2], groups[group * 2 + 1]).toString();
0N/A }
0N/A
0N/A /**
906N/A * Returns the input subsequence captured by the given
906N/A * <a href="Pattern.html#groupname">named-capturing group</a> during the previous
906N/A * match operation.
906N/A *
906N/A * <p> If the match was successful but the group specified failed to match
906N/A * any part of the input sequence, then <tt>null</tt> is returned. Note
906N/A * that some groups, for example <tt>(a*)</tt>, match the empty string.
906N/A * This method will return the empty string when such a group successfully
906N/A * matches the empty string in the input. </p>
906N/A *
906N/A * @param name
906N/A * The name of a named-capturing group in this matcher's pattern
906N/A *
906N/A * @return The (possibly empty) subsequence captured by the named group
906N/A * during the previous match, or <tt>null</tt> if the group
906N/A * failed to match part of the input
906N/A *
906N/A * @throws IllegalStateException
906N/A * If no match has yet been attempted,
906N/A * or if the previous match operation failed
906N/A *
906N/A * @throws IllegalArgumentException
906N/A * If there is no capturing group in the pattern
906N/A * with the given name
4362N/A * @since 1.7
906N/A */
906N/A public String group(String name) {
906N/A if (name == null)
906N/A throw new NullPointerException("Null group name");
906N/A if (first < 0)
906N/A throw new IllegalStateException("No match found");
906N/A if (!parentPattern.namedGroups().containsKey(name))
906N/A throw new IllegalArgumentException("No group with name <" + name + ">");
906N/A int group = parentPattern.namedGroups().get(name);
906N/A if ((groups[group*2] == -1) || (groups[group*2+1] == -1))
906N/A return null;
906N/A return getSubSequence(groups[group * 2], groups[group * 2 + 1]).toString();
906N/A }
906N/A
906N/A /**
0N/A * Returns the number of capturing groups in this matcher's pattern.
0N/A *
0N/A * <p> Group zero denotes the entire pattern by convention. It is not
0N/A * included in this count.
0N/A *
0N/A * <p> Any non-negative integer smaller than or equal to the value
0N/A * returned by this method is guaranteed to be a valid group index for
0N/A * this matcher. </p>
0N/A *
0N/A * @return The number of capturing groups in this matcher's pattern
0N/A */
0N/A public int groupCount() {
0N/A return parentPattern.capturingGroupCount - 1;
0N/A }
0N/A
0N/A /**
0N/A * Attempts to match the entire region against the pattern.
0N/A *
0N/A * <p> If the match succeeds then more information can be obtained via the
0N/A * <tt>start</tt>, <tt>end</tt>, and <tt>group</tt> methods. </p>
0N/A *
0N/A * @return <tt>true</tt> if, and only if, the entire region sequence
0N/A * matches this matcher's pattern
0N/A */
0N/A public boolean matches() {
0N/A return match(from, ENDANCHOR);
0N/A }
0N/A
0N/A /**
0N/A * Attempts to find the next subsequence of the input sequence that matches
0N/A * the pattern.
0N/A *
0N/A * <p> This method starts at the beginning of this matcher's region, or, if
0N/A * a previous invocation of the method was successful and the matcher has
0N/A * not since been reset, at the first character not matched by the previous
0N/A * match.
0N/A *
0N/A * <p> If the match succeeds then more information can be obtained via the
0N/A * <tt>start</tt>, <tt>end</tt>, and <tt>group</tt> methods. </p>
0N/A *
0N/A * @return <tt>true</tt> if, and only if, a subsequence of the input
0N/A * sequence matches this matcher's pattern
0N/A */
0N/A public boolean find() {
0N/A int nextSearchIndex = last;
0N/A if (nextSearchIndex == first)
0N/A nextSearchIndex++;
0N/A
0N/A // If next search starts before region, start it at region
0N/A if (nextSearchIndex < from)
0N/A nextSearchIndex = from;
0N/A
0N/A // If next search starts beyond region then it fails
0N/A if (nextSearchIndex > to) {
0N/A for (int i = 0; i < groups.length; i++)
0N/A groups[i] = -1;
0N/A return false;
0N/A }
0N/A return search(nextSearchIndex);
0N/A }
0N/A
0N/A /**
0N/A * Resets this matcher and then attempts to find the next subsequence of
0N/A * the input sequence that matches the pattern, starting at the specified
0N/A * index.
0N/A *
0N/A * <p> If the match succeeds then more information can be obtained via the
0N/A * <tt>start</tt>, <tt>end</tt>, and <tt>group</tt> methods, and subsequent
0N/A * invocations of the {@link #find()} method will start at the first
0N/A * character not matched by this match. </p>
0N/A *
0N/A * @throws IndexOutOfBoundsException
0N/A * If start is less than zero or if start is greater than the
0N/A * length of the input sequence.
0N/A *
0N/A * @return <tt>true</tt> if, and only if, a subsequence of the input
0N/A * sequence starting at the given index matches this matcher's
0N/A * pattern
0N/A */
0N/A public boolean find(int start) {
0N/A int limit = getTextLength();
0N/A if ((start < 0) || (start > limit))
0N/A throw new IndexOutOfBoundsException("Illegal start index");
0N/A reset();
0N/A return search(start);
0N/A }
0N/A
0N/A /**
0N/A * Attempts to match the input sequence, starting at the beginning of the
0N/A * region, against the pattern.
0N/A *
0N/A * <p> Like the {@link #matches matches} method, this method always starts
0N/A * at the beginning of the region; unlike that method, it does not
0N/A * require that the entire region be matched.
0N/A *
0N/A * <p> If the match succeeds then more information can be obtained via the
0N/A * <tt>start</tt>, <tt>end</tt>, and <tt>group</tt> methods. </p>
0N/A *
0N/A * @return <tt>true</tt> if, and only if, a prefix of the input
0N/A * sequence matches this matcher's pattern
0N/A */
0N/A public boolean lookingAt() {
0N/A return match(from, NOANCHOR);
0N/A }
0N/A
0N/A /**
0N/A * Returns a literal replacement <code>String</code> for the specified
0N/A * <code>String</code>.
0N/A *
0N/A * This method produces a <code>String</code> that will work
0N/A * as a literal replacement <code>s</code> in the
0N/A * <code>appendReplacement</code> method of the {@link Matcher} class.
0N/A * The <code>String</code> produced will match the sequence of characters
0N/A * in <code>s</code> treated as a literal sequence. Slashes ('\') and
0N/A * dollar signs ('$') will be given no special meaning.
0N/A *
0N/A * @param s The string to be literalized
0N/A * @return A literal string replacement
0N/A * @since 1.5
0N/A */
0N/A public static String quoteReplacement(String s) {
0N/A if ((s.indexOf('\\') == -1) && (s.indexOf('$') == -1))
0N/A return s;
0N/A StringBuilder sb = new StringBuilder();
0N/A for (int i=0; i<s.length(); i++) {
0N/A char c = s.charAt(i);
0N/A if (c == '\\' || c == '$') {
0N/A sb.append('\\');
0N/A }
0N/A sb.append(c);
0N/A }
0N/A return sb.toString();
0N/A }
0N/A
0N/A /**
0N/A * Implements a non-terminal append-and-replace step.
0N/A *
0N/A * <p> This method performs the following actions: </p>
0N/A *
0N/A * <ol>
0N/A *
0N/A * <li><p> It reads characters from the input sequence, starting at the
0N/A * append position, and appends them to the given string buffer. It
0N/A * stops after reading the last character preceding the previous match,
0N/A * that is, the character at index {@link
0N/A * #start()}&nbsp;<tt>-</tt>&nbsp;<tt>1</tt>. </p></li>
0N/A *
0N/A * <li><p> It appends the given replacement string to the string buffer.
0N/A * </p></li>
0N/A *
0N/A * <li><p> It sets the append position of this matcher to the index of
0N/A * the last character matched, plus one, that is, to {@link #end()}.
0N/A * </p></li>
0N/A *
0N/A * </ol>
0N/A *
0N/A * <p> The replacement string may contain references to subsequences
0N/A * captured during the previous match: Each occurrence of
1795N/A * <tt>${</tt><i>name</i><tt>}</tt> or <tt>$</tt><i>g</i>
906N/A * will be replaced by the result of evaluating the corresponding
906N/A * {@link #group(String) group(name)} or {@link #group(int) group(g)</tt>}
906N/A * respectively. For <tt>$</tt><i>g</i><tt></tt>,
906N/A * the first number after the <tt>$</tt> is always treated as part of
0N/A * the group reference. Subsequent numbers are incorporated into g if
0N/A * they would form a legal group reference. Only the numerals '0'
0N/A * through '9' are considered as potential components of the group
0N/A * reference. If the second group matched the string <tt>"foo"</tt>, for
0N/A * example, then passing the replacement string <tt>"$2bar"</tt> would
0N/A * cause <tt>"foobar"</tt> to be appended to the string buffer. A dollar
0N/A * sign (<tt>$</tt>) may be included as a literal in the replacement
0N/A * string by preceding it with a backslash (<tt>\$</tt>).
0N/A *
0N/A * <p> Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in
0N/A * the replacement string may cause the results to be different than if it
0N/A * were being treated as a literal replacement string. Dollar signs may be
0N/A * treated as references to captured subsequences as described above, and
0N/A * backslashes are used to escape literal characters in the replacement
0N/A * string.
0N/A *
0N/A * <p> This method is intended to be used in a loop together with the
0N/A * {@link #appendTail appendTail} and {@link #find find} methods. The
0N/A * following code, for example, writes <tt>one dog two dogs in the
0N/A * yard</tt> to the standard-output stream: </p>
0N/A *
0N/A * <blockquote><pre>
0N/A * Pattern p = Pattern.compile("cat");
0N/A * Matcher m = p.matcher("one cat two cats in the yard");
0N/A * StringBuffer sb = new StringBuffer();
0N/A * while (m.find()) {
0N/A * m.appendReplacement(sb, "dog");
0N/A * }
0N/A * m.appendTail(sb);
0N/A * System.out.println(sb.toString());</pre></blockquote>
0N/A *
0N/A * @param sb
0N/A * The target string buffer
0N/A *
0N/A * @param replacement
0N/A * The replacement string
0N/A *
0N/A * @return This matcher
0N/A *
0N/A * @throws IllegalStateException
0N/A * If no match has yet been attempted,
0N/A * or if the previous match operation failed
0N/A *
906N/A * @throws IllegalArgumentException
906N/A * If the replacement string refers to a named-capturing
906N/A * group that does not exist in the pattern
906N/A *
0N/A * @throws IndexOutOfBoundsException
0N/A * If the replacement string refers to a capturing group
0N/A * that does not exist in the pattern
0N/A */
0N/A public Matcher appendReplacement(StringBuffer sb, String replacement) {
0N/A
0N/A // If no match, return error
0N/A if (first < 0)
0N/A throw new IllegalStateException("No match available");
0N/A
0N/A // Process substitution string to replace group references with groups
0N/A int cursor = 0;
0N/A StringBuilder result = new StringBuilder();
0N/A
0N/A while (cursor < replacement.length()) {
0N/A char nextChar = replacement.charAt(cursor);
0N/A if (nextChar == '\\') {
0N/A cursor++;
0N/A nextChar = replacement.charAt(cursor);
0N/A result.append(nextChar);
0N/A cursor++;
0N/A } else if (nextChar == '$') {
0N/A // Skip past $
0N/A cursor++;
906N/A // A StringIndexOutOfBoundsException is thrown if
906N/A // this "$" is the last character in replacement
906N/A // string in current implementation, a IAE might be
906N/A // more appropriate.
906N/A nextChar = replacement.charAt(cursor);
906N/A int refNum = -1;
1795N/A if (nextChar == '{') {
906N/A cursor++;
906N/A StringBuilder gsb = new StringBuilder();
906N/A while (cursor < replacement.length()) {
906N/A nextChar = replacement.charAt(cursor);
906N/A if (ASCII.isLower(nextChar) ||
906N/A ASCII.isUpper(nextChar) ||
906N/A ASCII.isDigit(nextChar)) {
906N/A gsb.append(nextChar);
906N/A cursor++;
906N/A } else {
906N/A break;
906N/A }
0N/A }
906N/A if (gsb.length() == 0)
906N/A throw new IllegalArgumentException(
906N/A "named capturing group has 0 length name");
1795N/A if (nextChar != '}')
906N/A throw new IllegalArgumentException(
1795N/A "named capturing group is missing trailing '}'");
906N/A String gname = gsb.toString();
1795N/A if (ASCII.isDigit(gname.charAt(0)))
1795N/A throw new IllegalArgumentException(
1795N/A "capturing group name {" + gname +
1795N/A "} starts with digit character");
906N/A if (!parentPattern.namedGroups().containsKey(gname))
906N/A throw new IllegalArgumentException(
1795N/A "No group with name {" + gname + "}");
906N/A refNum = parentPattern.namedGroups().get(gname);
906N/A cursor++;
906N/A } else {
906N/A // The first number is always a group
906N/A refNum = (int)nextChar - '0';
906N/A if ((refNum < 0)||(refNum > 9))
906N/A throw new IllegalArgumentException(
906N/A "Illegal group reference");
906N/A cursor++;
906N/A // Capture the largest legal group string
906N/A boolean done = false;
906N/A while (!done) {
906N/A if (cursor >= replacement.length()) {
906N/A break;
906N/A }
906N/A int nextDigit = replacement.charAt(cursor) - '0';
906N/A if ((nextDigit < 0)||(nextDigit > 9)) { // not a number
906N/A break;
906N/A }
906N/A int newRefNum = (refNum * 10) + nextDigit;
906N/A if (groupCount() < newRefNum) {
906N/A done = true;
906N/A } else {
906N/A refNum = newRefNum;
906N/A cursor++;
906N/A }
0N/A }
0N/A }
0N/A // Append group
0N/A if (start(refNum) != -1 && end(refNum) != -1)
0N/A result.append(text, start(refNum), end(refNum));
0N/A } else {
0N/A result.append(nextChar);
0N/A cursor++;
0N/A }
0N/A }
0N/A // Append the intervening text
0N/A sb.append(text, lastAppendPosition, first);
0N/A // Append the match substitution
0N/A sb.append(result);
0N/A
0N/A lastAppendPosition = last;
0N/A return this;
0N/A }
0N/A
0N/A /**
0N/A * Implements a terminal append-and-replace step.
0N/A *
0N/A * <p> This method reads characters from the input sequence, starting at
0N/A * the append position, and appends them to the given string buffer. It is
0N/A * intended to be invoked after one or more invocations of the {@link
0N/A * #appendReplacement appendReplacement} method in order to copy the
0N/A * remainder of the input sequence. </p>
0N/A *
0N/A * @param sb
0N/A * The target string buffer
0N/A *
0N/A * @return The target string buffer
0N/A */
0N/A public StringBuffer appendTail(StringBuffer sb) {
0N/A sb.append(text, lastAppendPosition, getTextLength());
0N/A return sb;
0N/A }
0N/A
0N/A /**
0N/A * Replaces every subsequence of the input sequence that matches the
0N/A * pattern with the given replacement string.
0N/A *
0N/A * <p> This method first resets this matcher. It then scans the input
0N/A * sequence looking for matches of the pattern. Characters that are not
0N/A * part of any match are appended directly to the result string; each match
0N/A * is replaced in the result by the replacement string. The replacement
0N/A * string may contain references to captured subsequences as in the {@link
0N/A * #appendReplacement appendReplacement} method.
0N/A *
0N/A * <p> Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in
0N/A * the replacement string may cause the results to be different than if it
0N/A * were being treated as a literal replacement string. Dollar signs may be
0N/A * treated as references to captured subsequences as described above, and
0N/A * backslashes are used to escape literal characters in the replacement
0N/A * string.
0N/A *
0N/A * <p> Given the regular expression <tt>a*b</tt>, the input
0N/A * <tt>"aabfooaabfooabfoob"</tt>, and the replacement string
0N/A * <tt>"-"</tt>, an invocation of this method on a matcher for that
0N/A * expression would yield the string <tt>"-foo-foo-foo-"</tt>.
0N/A *
0N/A * <p> Invoking this method changes this matcher's state. If the matcher
0N/A * is to be used in further matching operations then it should first be
0N/A * reset. </p>
0N/A *
0N/A * @param replacement
0N/A * The replacement string
0N/A *
0N/A * @return The string constructed by replacing each matching subsequence
0N/A * by the replacement string, substituting captured subsequences
0N/A * as needed
0N/A */
0N/A public String replaceAll(String replacement) {
0N/A reset();
0N/A boolean result = find();
0N/A if (result) {
0N/A StringBuffer sb = new StringBuffer();
0N/A do {
0N/A appendReplacement(sb, replacement);
0N/A result = find();
0N/A } while (result);
0N/A appendTail(sb);
0N/A return sb.toString();
0N/A }
0N/A return text.toString();
0N/A }
0N/A
0N/A /**
0N/A * Replaces the first subsequence of the input sequence that matches the
0N/A * pattern with the given replacement string.
0N/A *
0N/A * <p> This method first resets this matcher. It then scans the input
0N/A * sequence looking for a match of the pattern. Characters that are not
0N/A * part of the match are appended directly to the result string; the match
0N/A * is replaced in the result by the replacement string. The replacement
0N/A * string may contain references to captured subsequences as in the {@link
0N/A * #appendReplacement appendReplacement} method.
0N/A *
0N/A * <p>Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in
0N/A * the replacement string may cause the results to be different than if it
0N/A * were being treated as a literal replacement string. Dollar signs may be
0N/A * treated as references to captured subsequences as described above, and
0N/A * backslashes are used to escape literal characters in the replacement
0N/A * string.
0N/A *
0N/A * <p> Given the regular expression <tt>dog</tt>, the input
0N/A * <tt>"zzzdogzzzdogzzz"</tt>, and the replacement string
0N/A * <tt>"cat"</tt>, an invocation of this method on a matcher for that
0N/A * expression would yield the string <tt>"zzzcatzzzdogzzz"</tt>. </p>
0N/A *
0N/A * <p> Invoking this method changes this matcher's state. If the matcher
0N/A * is to be used in further matching operations then it should first be
0N/A * reset. </p>
0N/A *
0N/A * @param replacement
0N/A * The replacement string
0N/A * @return The string constructed by replacing the first matching
0N/A * subsequence by the replacement string, substituting captured
0N/A * subsequences as needed
0N/A */
0N/A public String replaceFirst(String replacement) {
0N/A if (replacement == null)
0N/A throw new NullPointerException("replacement");
0N/A reset();
0N/A if (!find())
0N/A return text.toString();
0N/A StringBuffer sb = new StringBuffer();
0N/A appendReplacement(sb, replacement);
0N/A appendTail(sb);
0N/A return sb.toString();
0N/A }
0N/A
0N/A /**
0N/A * Sets the limits of this matcher's region. The region is the part of the
0N/A * input sequence that will be searched to find a match. Invoking this
0N/A * method resets the matcher, and then sets the region to start at the
0N/A * index specified by the <code>start</code> parameter and end at the
0N/A * index specified by the <code>end</code> parameter.
0N/A *
0N/A * <p>Depending on the transparency and anchoring being used (see
0N/A * {@link #useTransparentBounds useTransparentBounds} and
0N/A * {@link #useAnchoringBounds useAnchoringBounds}), certain constructs such
0N/A * as anchors may behave differently at or around the boundaries of the
0N/A * region.
0N/A *
0N/A * @param start
0N/A * The index to start searching at (inclusive)
0N/A * @param end
0N/A * The index to end searching at (exclusive)
0N/A * @throws IndexOutOfBoundsException
0N/A * If start or end is less than zero, if
0N/A * start is greater than the length of the input sequence, if
0N/A * end is greater than the length of the input sequence, or if
0N/A * start is greater than end.
0N/A * @return this matcher
0N/A * @since 1.5
0N/A */
0N/A public Matcher region(int start, int end) {
0N/A if ((start < 0) || (start > getTextLength()))
0N/A throw new IndexOutOfBoundsException("start");
0N/A if ((end < 0) || (end > getTextLength()))
0N/A throw new IndexOutOfBoundsException("end");
0N/A if (start > end)
0N/A throw new IndexOutOfBoundsException("start > end");
0N/A reset();
0N/A from = start;
0N/A to = end;
0N/A return this;
0N/A }
0N/A
0N/A /**
0N/A * Reports the start index of this matcher's region. The
0N/A * searches this matcher conducts are limited to finding matches
0N/A * within {@link #regionStart regionStart} (inclusive) and
0N/A * {@link #regionEnd regionEnd} (exclusive).
0N/A *
0N/A * @return The starting point of this matcher's region
0N/A * @since 1.5
0N/A */
0N/A public int regionStart() {
0N/A return from;
0N/A }
0N/A
0N/A /**
0N/A * Reports the end index (exclusive) of this matcher's region.
0N/A * The searches this matcher conducts are limited to finding matches
0N/A * within {@link #regionStart regionStart} (inclusive) and
0N/A * {@link #regionEnd regionEnd} (exclusive).
0N/A *
0N/A * @return the ending point of this matcher's region
0N/A * @since 1.5
0N/A */
0N/A public int regionEnd() {
0N/A return to;
0N/A }
0N/A
0N/A /**
0N/A * Queries the transparency of region bounds for this matcher.
0N/A *
0N/A * <p> This method returns <tt>true</tt> if this matcher uses
0N/A * <i>transparent</i> bounds, <tt>false</tt> if it uses <i>opaque</i>
0N/A * bounds.
0N/A *
0N/A * <p> See {@link #useTransparentBounds useTransparentBounds} for a
0N/A * description of transparent and opaque bounds.
0N/A *
0N/A * <p> By default, a matcher uses opaque region boundaries.
0N/A *
0N/A * @return <tt>true</tt> iff this matcher is using transparent bounds,
0N/A * <tt>false</tt> otherwise.
0N/A * @see java.util.regex.Matcher#useTransparentBounds(boolean)
0N/A * @since 1.5
0N/A */
0N/A public boolean hasTransparentBounds() {
0N/A return transparentBounds;
0N/A }
0N/A
0N/A /**
0N/A * Sets the transparency of region bounds for this matcher.
0N/A *
0N/A * <p> Invoking this method with an argument of <tt>true</tt> will set this
0N/A * matcher to use <i>transparent</i> bounds. If the boolean
0N/A * argument is <tt>false</tt>, then <i>opaque</i> bounds will be used.
0N/A *
0N/A * <p> Using transparent bounds, the boundaries of this
0N/A * matcher's region are transparent to lookahead, lookbehind,
0N/A * and boundary matching constructs. Those constructs can see beyond the
0N/A * boundaries of the region to see if a match is appropriate.
0N/A *
0N/A * <p> Using opaque bounds, the boundaries of this matcher's
0N/A * region are opaque to lookahead, lookbehind, and boundary matching
0N/A * constructs that may try to see beyond them. Those constructs cannot
0N/A * look past the boundaries so they will fail to match anything outside
0N/A * of the region.
0N/A *
0N/A * <p> By default, a matcher uses opaque bounds.
0N/A *
0N/A * @param b a boolean indicating whether to use opaque or transparent
0N/A * regions
0N/A * @return this matcher
0N/A * @see java.util.regex.Matcher#hasTransparentBounds
0N/A * @since 1.5
0N/A */
0N/A public Matcher useTransparentBounds(boolean b) {
0N/A transparentBounds = b;
0N/A return this;
0N/A }
0N/A
0N/A /**
0N/A * Queries the anchoring of region bounds for this matcher.
0N/A *
0N/A * <p> This method returns <tt>true</tt> if this matcher uses
0N/A * <i>anchoring</i> bounds, <tt>false</tt> otherwise.
0N/A *
0N/A * <p> See {@link #useAnchoringBounds useAnchoringBounds} for a
0N/A * description of anchoring bounds.
0N/A *
0N/A * <p> By default, a matcher uses anchoring region boundaries.
0N/A *
0N/A * @return <tt>true</tt> iff this matcher is using anchoring bounds,
0N/A * <tt>false</tt> otherwise.
0N/A * @see java.util.regex.Matcher#useAnchoringBounds(boolean)
0N/A * @since 1.5
0N/A */
0N/A public boolean hasAnchoringBounds() {
0N/A return anchoringBounds;
0N/A }
0N/A
0N/A /**
0N/A * Sets the anchoring of region bounds for this matcher.
0N/A *
0N/A * <p> Invoking this method with an argument of <tt>true</tt> will set this
0N/A * matcher to use <i>anchoring</i> bounds. If the boolean
0N/A * argument is <tt>false</tt>, then <i>non-anchoring</i> bounds will be
0N/A * used.
0N/A *
0N/A * <p> Using anchoring bounds, the boundaries of this
0N/A * matcher's region match anchors such as ^ and $.
0N/A *
0N/A * <p> Without anchoring bounds, the boundaries of this
0N/A * matcher's region will not match anchors such as ^ and $.
0N/A *
0N/A * <p> By default, a matcher uses anchoring region boundaries.
0N/A *
0N/A * @param b a boolean indicating whether or not to use anchoring bounds.
0N/A * @return this matcher
0N/A * @see java.util.regex.Matcher#hasAnchoringBounds
0N/A * @since 1.5
0N/A */
0N/A public Matcher useAnchoringBounds(boolean b) {
0N/A anchoringBounds = b;
0N/A return this;
0N/A }
0N/A
0N/A /**
0N/A * <p>Returns the string representation of this matcher. The
0N/A * string representation of a <code>Matcher</code> contains information
0N/A * that may be useful for debugging. The exact format is unspecified.
0N/A *
0N/A * @return The string representation of this matcher
0N/A * @since 1.5
0N/A */
0N/A public String toString() {
0N/A StringBuilder sb = new StringBuilder();
0N/A sb.append("java.util.regex.Matcher");
0N/A sb.append("[pattern=" + pattern());
0N/A sb.append(" region=");
0N/A sb.append(regionStart() + "," + regionEnd());
0N/A sb.append(" lastmatch=");
0N/A if ((first >= 0) && (group() != null)) {
0N/A sb.append(group());
0N/A }
0N/A sb.append("]");
0N/A return sb.toString();
0N/A }
0N/A
0N/A /**
0N/A * <p>Returns true if the end of input was hit by the search engine in
0N/A * the last match operation performed by this matcher.
0N/A *
0N/A * <p>When this method returns true, then it is possible that more input
0N/A * would have changed the result of the last search.
0N/A *
0N/A * @return true iff the end of input was hit in the last match; false
0N/A * otherwise
0N/A * @since 1.5
0N/A */
0N/A public boolean hitEnd() {
0N/A return hitEnd;
0N/A }
0N/A
0N/A /**
0N/A * <p>Returns true if more input could change a positive match into a
0N/A * negative one.
0N/A *
0N/A * <p>If this method returns true, and a match was found, then more
0N/A * input could cause the match to be lost. If this method returns false
0N/A * and a match was found, then more input might change the match but the
0N/A * match won't be lost. If a match was not found, then requireEnd has no
0N/A * meaning.
0N/A *
0N/A * @return true iff more input could change a positive match into a
0N/A * negative one.
0N/A * @since 1.5
0N/A */
0N/A public boolean requireEnd() {
0N/A return requireEnd;
0N/A }
0N/A
0N/A /**
0N/A * Initiates a search to find a Pattern within the given bounds.
0N/A * The groups are filled with default values and the match of the root
0N/A * of the state machine is called. The state machine will hold the state
0N/A * of the match as it proceeds in this matcher.
0N/A *
0N/A * Matcher.from is not set here, because it is the "hard" boundary
0N/A * of the start of the search which anchors will set to. The from param
0N/A * is the "soft" boundary of the start of the search, meaning that the
0N/A * regex tries to match at that index but ^ won't match there. Subsequent
0N/A * calls to the search methods start at a new "soft" boundary which is
0N/A * the end of the previous match.
0N/A */
0N/A boolean search(int from) {
0N/A this.hitEnd = false;
0N/A this.requireEnd = false;
0N/A from = from < 0 ? 0 : from;
0N/A this.first = from;
0N/A this.oldLast = oldLast < 0 ? from : oldLast;
0N/A for (int i = 0; i < groups.length; i++)
0N/A groups[i] = -1;
0N/A acceptMode = NOANCHOR;
0N/A boolean result = parentPattern.root.match(this, from, text);
0N/A if (!result)
0N/A this.first = -1;
0N/A this.oldLast = this.last;
0N/A return result;
0N/A }
0N/A
0N/A /**
0N/A * Initiates a search for an anchored match to a Pattern within the given
0N/A * bounds. The groups are filled with default values and the match of the
0N/A * root of the state machine is called. The state machine will hold the
0N/A * state of the match as it proceeds in this matcher.
0N/A */
0N/A boolean match(int from, int anchor) {
0N/A this.hitEnd = false;
0N/A this.requireEnd = false;
0N/A from = from < 0 ? 0 : from;
0N/A this.first = from;
0N/A this.oldLast = oldLast < 0 ? from : oldLast;
0N/A for (int i = 0; i < groups.length; i++)
0N/A groups[i] = -1;
0N/A acceptMode = anchor;
0N/A boolean result = parentPattern.matchRoot.match(this, from, text);
0N/A if (!result)
0N/A this.first = -1;
0N/A this.oldLast = this.last;
0N/A return result;
0N/A }
0N/A
0N/A /**
0N/A * Returns the end index of the text.
0N/A *
0N/A * @return the index after the last character in the text
0N/A */
0N/A int getTextLength() {
0N/A return text.length();
0N/A }
0N/A
0N/A /**
0N/A * Generates a String from this Matcher's input in the specified range.
0N/A *
0N/A * @param beginIndex the beginning index, inclusive
0N/A * @param endIndex the ending index, exclusive
0N/A * @return A String generated from this Matcher's input
0N/A */
0N/A CharSequence getSubSequence(int beginIndex, int endIndex) {
0N/A return text.subSequence(beginIndex, endIndex);
0N/A }
0N/A
0N/A /**
0N/A * Returns this Matcher's input character at index i.
0N/A *
0N/A * @return A char from the specified index
0N/A */
0N/A char charAt(int i) {
0N/A return text.charAt(i);
0N/A }
0N/A
0N/A}