Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Part of a series of educational regex articles, this is a gentle introduction to the concept of nested references. The first few triangular numbers are: 1 = 1 3 = 1 + 2 6 = 1 + 2 + 3 10 = 1 + 2 + 3 + 4 15 = 1 + 2 + 3 + 4 + 5 There are many ways to check if a number is triangular. There's this interesting technique that uses regular expressions as follows: Given n, we first create a...
It is my understanding that the java.regex package does not have support for named groups (http://www.regular-expressions.info/named.html) so can anyone point me towards a third-party library that does? I've looked at jregex but its last release was in 2002 and it didn't work for me (admittedly I only tried briefly) under java5.
I am new to Java Regular expression. We are using a pattern for matching a string. We are using this for validating a text field and it meets our requirements. But there is a performance issue in the matching. Pattern : ([a-zA-Z0-9]+[ ]?(([_\-][a-zA-Z0-9 ])*)?[_\-]?)+ Input text should start with a-zA-Z0-9. Space(single) is allowed between words "_" and "-" are allowed but cannot be consecut...
I'm trying to convert "\something\" into "\\something\\" using replaceAll, but I keep getting all kinds of errors. I thought this was the solution: theString.replaceAll("\\", "\\\\"); But this gives: Exception in thread "main" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
My understanding is that Java's implementation of regular expressions is based on Perl's. However, in the following example, if I execute the same regex with the same string, Java and Perl return different results. Here's the Java example: public class RegexTest { public static void main( String args[] ) { String sentence = "This is a test of regular expressions."; System...
My first question and Im excited... I've lurked since go-live and love the site, however I apologize for any newbie errors, formatting, etc... I'm attempting to validate the format of a string field that contains a date in Java. We will receive the date in a string, I will validate its format before parsing it into a real Date object. The format being passed in is in the YYYY-MM-DD format...
I have a function that uses Pattern.compile and a Matcher to search a list of strings for a pattern. This function is used in multiple threads. Each thread will have a unique pattern passed to the Pattern.compile when the thread is created. The number of threads and patterns are dynamic, meaning that I can add more patterns and threads during configuration. Do I need to put a "synchronize" ...
Is there any String replacement mechanism in Java, where I can pass objects with a text, and it replaces the string as it occurs. For example, the text is : Hello ${user.name}, Welcome to ${site.name}. The objects I have are "user" and "site". I want to replace the strings given inside ${} with its equivalent values from the objects. This is same as we replace objects in a velocity temp...
Is there any way to replace a regexp with modified content of capture group? Example: Pattern regex = Pattern.compile("(\\d{1,2})"); Matcher regexMatcher = regex.matcher(text); resultString = regexMatcher.replaceAll("$1"); // *3 ?? And I'd like to replace all occurrence with $1 multiplied by 3. edit: Looks like, something's wrong :( If I use Pattern regex = Pattern.compile("(\\d{1,2})")...
In my quest to correctly grasp Interface best practices, I have noticed declarations such as: List<String> myList = new ArrayList<String>(); instead of ArrayList<String> myList = new ArrayList<String>(); -To my understanding the reason is because it allows flexibility in case one day you do not want to implement an ArrayList but maybe another type of list. With t...
I am trying to use a simple split to break up the following string: 00-00000 My expression is: ^([0-9][0-9])(-)([0-9])([0-9])([0-9])([0-9])([0-9]) And my usage is: String s = "00-00000"; String pattern = "^([0-9][0-9])(-)([0-9])([0-9])([0-9])([0-9])([0-9])"; String[] parts = s.split(pattern); If I play around with the Pattern and Matcher classes I can see that my pattern does match and t...
Say I'm running a service where users can submit a regex to search through lots of data. If the user submits a regex that is very slow (ie. takes minutes for Matcher.find() to return), I want a way to cancel that match. The only way I can think of doing this is to have another thread monitor how long a match is taking and use Thread.stop() to cancel it if necessary. Member variables: long REG...
I need help to replace all \n (new line) caracters for in a String, but not those \n inside [code][/code] tags. My brain is burning, I can't solve this by my own :( Example: test test test test test test test test [code]some test code [/code] more text Should be: test test test<br /> test test test<br /> test<br /> test<br /> <br /> [code]some test code [/c...
So if I wished to replace all numbers with a given value, I could just use "hello8".replaceAll("[1-9]", "!"); --> hello! Now is there a way to get the number that is actually being matched and add that in the mix? e.g. --> hello!8
trivial regex question (the answer is most probably Java-specific): "#This is a comment in a file".matches("^#") This returns false. As far as I can see, ^ means what it always means and # has no special meaning, so I'd translate ^# as "A '#' at the beginning of the string". Which should match. And so it does, in Perl: perl -e "print '#This is a comment'=~/^#/;" prints "1". So I'm pretty ...
i have this homework problem where i need to use regex to remove every other character in a string. in one part, i have to delete characters at index 1,3,5,.... i have done this as follows: String s = "1a2b3c4d5"; System.out.println(s.replaceAll("(.).", "$1")); this prints 12345 which is what i want. essentially i match two characters at a time, and replacing with the first character. i use...
I have a directory like this and I am trying to extract the word "photon" from just before "photon.exe". C:\workspace\photon\output\i686\diagnostic\photon.exe(Suspended) Thread(Running) My code looks like this: String path = "C:\workspace\photon\output\i686\diagnostic\photon.exe(Suspended) Thread(Running)"; Pattern pattern = Pattern.compile(".+\\\\(.+).exe"); Matcher matcher = pattern.match...
Can anyone explain: Why the two patterns used below give different results? (answered below) Why the 2nd example gives a group count of 1 but says the start and end of group 1 is -1? public void testGroups() throws Exception { String TEST_STRING = "After Yes is group 1 End"; { Pattern p; Matcher m; String pattern="(?:Yes|No)(.*)End"; p=Pattern.compile(pattern); m=p.matc...
i want to match something like aaaa, aaaad, adjjjjk. Something like this ([a-z])\1+ was used to match the repeated characters but i am not able to figure this out for 4 letters.
I have to write some sort of parser that get a String and replace certain sets of character with others. The code looks like this: noHTMLString = noHTMLString.replaceAll("</p>", "\n"); noHTMLString = noHTMLString.replaceAll("<br/>", "\n\n"); noHTMLString = noHTMLString.replaceAll("<br />", "\n\n"); //here goes A LOT of lines like these ones The function is very long and per...
In PHP if we need to match a something like, ["one","two","three"], we could use the following regular expression with preg_match. $pattern = "/\[\"(\w+)\",\"(\w+)\",\"(\w+)\"\]/" By using the parenthesis we are also able to extract the words one, two and three. I am aware of the Matcher object in Java, but am unable to get similar functionality; I am only able to extract the entire string. ...
   /*
    * Copyright 1999-2006 Sun Microsystems, Inc.  All Rights Reserved.
    * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    *
    * This code is free software; you can redistribute it and/or modify it
    * under the terms of the GNU General Public License version 2 only, as
    * published by the Free Software Foundation.  Sun designates this
    * particular file as subject to the "Classpath" exception as provided
    * by Sun in the LICENSE file that accompanied this code.
   *
   * This code 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
   * version 2 for more details (a copy is included in the LICENSE file that
   * accompanied this code).
   *
   * You should have received a copy of the GNU General Public License version
   * 2 along with this work; if not, write to the Free Software Foundation,
   * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   *
   * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   * CA 95054 USA or visit www.sun.com if you need additional information or
   * have any questions.
   */
  
  package java.util.regex;


An engine that performs match operations on a character sequence by interpreting a Pattern.

A matcher is created from a pattern by invoking the pattern's Pattern.matcher(java.lang.CharSequence) method. Once created, a matcher can be used to perform three different kinds of match operations:

  • The matches method attempts to match the entire input sequence against the pattern.

  • The lookingAt method attempts to match the input sequence, starting at the beginning, against the pattern.

  • The find method scans the input sequence looking for the next subsequence that matches the pattern.

Each of these methods returns a boolean indicating success or failure. More information about a successful match can be obtained by querying the state of the matcher.

A matcher finds matches in a subset of its input called the region. By default, the region contains all of the matcher's input. The region can be modified via theregion method and queried via the regionStart and regionEnd methods. The way that the region boundaries interact with some pattern constructs can be changed. See useAnchoringBounds and useTransparentBounds for more details.

This class also defines methods for replacing matched subsequences with new strings whose contents can, if desired, be computed from the match result. The appendReplacement and appendTail(java.lang.StringBuffer) methods can be used in tandem in order to collect the result into an existing string buffer, or the more convenient replaceAll(java.lang.String) method can be used to create a string in which every matching subsequence in the input sequence is replaced.

The explicit state of a matcher includes the start and end indices of the most recent successful match. It also includes the start and end indices of the input subsequence captured by each capturing group in the pattern as well as a total count of such subsequences. As a convenience, methods are also provided for returning these captured subsequences in string form.

The explicit state of a matcher is initially undefined; attempting to query any part of it before a successful match will cause an java.lang.IllegalStateException to be thrown. The explicit state of a matcher is recomputed by every match operation.

The implicit state of a matcher includes the input character sequence as well as the append position, which is initially zero and is updated by the appendReplacement method.

A matcher may be reset explicitly by invoking its reset() method or, if a new input sequence is desired, its reset(java.lang.CharSequence) method. Resetting a matcher discards its explicit state information and sets the append position to zero.

Instances of this class are not safe for use by multiple concurrent threads.

Author(s):
Mike McCloskey
Mark Reinhold
JSR-51 Expert Group
Since:
1.4
Spec:
JSR-51
 
 
 public final class Matcher implements MatchResult {

    
The Pattern object that created this Matcher.
 
     Pattern parentPattern;

    
The storage used by groups. They may contain invalid values if a group was skipped during the matching.
 
     int[] groups;

    
The range within the sequence that is to be matched. Anchors will match at these "hard" boundaries. Changing the region changes these values.
 
     int fromto;

    
Lookbehind uses this value to ensure that the subexpression match ends at the point where the lookbehind was encountered.
 
     int lookbehindTo;

    
The original string being matched.
 
     CharSequence text;

    
Matcher state used by the last node. NOANCHOR is used when a match does not have to consume all of the input. ENDANCHOR is the mode used for matching all the input.
 
     static final int ENDANCHOR = 1;
     static final int NOANCHOR = 0;
     int acceptMode = ;

    
The range of string that last matched the pattern. If the last match failed then first is -1; last initially holds 0 then it holds the index of the end of the last match (which is where the next search starts).
 
     int first = -1, last = 0;

    
The end index of what matched in the last match operation.
 
     int oldLast = -1;

    
The index of the last position appended in a substitution.
 
     int lastAppendPosition = 0;

    
Storage used by nodes to tell what repetition they are on in a pattern, and where groups begin. The nodes themselves are stateless, so they rely on this field to hold state during a match.
 
     int[] locals;

    
Boolean indicating whether or not more input could change the results of the last match. If hitEnd is true, and a match was found, then more input might cause a different match to be found. If hitEnd is true and a match was not found, then more input could cause a match to be found. If hitEnd is false and a match was found, then more input will not change the match. If hitEnd is false and a match was not found, then more input will not cause a match to be found.
 
     boolean hitEnd;

    
Boolean indicating whether or not more input could change a positive match into a negative one. If requireEnd is true, and a match was found, then more input could cause the match to be lost. If requireEnd is false and a match was found, then more input might change the match but the match won't be lost. If a match was not found, then requireEnd has no meaning.
 
     boolean requireEnd;

    
If transparentBounds is true then the boundaries of this matcher's region are transparent to lookahead, lookbehind, and boundary matching constructs that try to see beyond them.
 
     boolean transparentBounds = false;

    
If anchoringBounds is true then the boundaries of this matcher's region match anchors such as ^ and $.
 
     boolean anchoringBounds = true;

    
No default constructor.
 
     Matcher() {
     }

    
All matchers have the state used by Pattern during a match.
 
     Matcher(Pattern parentCharSequence text) {
         this. = parent;
         this. = text;
 
         // Allocate state storage
         int parentGroupCount = Math.max(parent.capturingGroupCount, 10);
          = new int[parentGroupCount * 2];
          = new int[parent.localCount];
 
         // Put fields into initial states
         reset();
     }

    
Returns the pattern that is interpreted by this matcher.

Returns:
The pattern for which this matcher was created
 
     public Pattern pattern() {
         return ;
     }

    
Returns the match state of this matcher as a MatchResult. The result is unaffected by subsequent operations performed upon this matcher.

Returns:
a MatchResult with the state of this matcher
Since:
1.5
 
     public MatchResult toMatchResult() {
         Matcher result = new Matcher(this..toString());
         result.first = this.;
         result.last = this.;
         result.groups = (int[])(this..clone());
         return result;
     }

    
Changes the Pattern that this Matcher uses to find matches with.

This method causes this matcher to lose information about the groups of the last match that occurred. The matcher's position in the input is maintained and its last append position is unaffected.

Parameters:
newPattern The new pattern used by this matcher
Returns:
This matcher
Throws:
java.lang.IllegalArgumentException If newPattern is null
Since:
1.5
 
     public Matcher usePattern(Pattern newPattern) {
         if (newPattern == null)
             throw new IllegalArgumentException("Pattern cannot be null");
          = newPattern;
 
         // Reallocate state storage
         int parentGroupCount = Math.max(newPattern.capturingGroupCount, 10);
          = new int[parentGroupCount * 2];
          = new int[newPattern.localCount];
         for (int i = 0; i < .i++)
             [i] = -1;
         for (int i = 0; i < .i++)
             [i] = -1;
         return this;
     }

    
Resets this matcher.

Resetting a matcher discards all of its explicit state information and sets its append position to zero. The matcher's region is set to the default region, which is its entire character sequence. The anchoring and transparency of this matcher's region boundaries are unaffected.

Returns:
This matcher
 
     public Matcher reset() {
          = -1;
          = 0;
          = -1;
         for(int i=0; i<.i++)
             [i] = -1;
         for(int i=0; i<.i++)
             [i] = -1;
          = 0;
          = 0;
          = getTextLength();
         return this;
     }

    
Resets this matcher with a new input sequence.

Resetting a matcher discards all of its explicit state information and sets its append position to zero. The matcher's region is set to the default region, which is its entire character sequence. The anchoring and transparency of this matcher's region boundaries are unaffected.

Parameters:
input The new input character sequence
Returns:
This matcher
 
     public Matcher reset(CharSequence input) {
          = input;
         return reset();
     }

    
Returns the start index of the previous match.

Returns:
The index of the first character matched
Throws:
java.lang.IllegalStateException If no match has yet been attempted, or if the previous match operation failed
 
     public int start() {
         if ( < 0)
             throw new IllegalStateException("No match available");
         return ;
     }

    
Returns the start index of the subsequence captured by the given group during the previous match operation.

Capturing groups are indexed from left to right, starting at one. Group zero denotes the entire pattern, so the expression m.start(0) is equivalent to m.start().

Parameters:
group The index of a capturing group in this matcher's pattern
Returns:
The index of the first character captured by the group, or -1 if the match was successful but the group itself did not match anything
Throws:
java.lang.IllegalStateException If no match has yet been attempted, or if the previous match operation failed
java.lang.IndexOutOfBoundsException If there is no capturing group in the pattern with the given index
 
     public int start(int group) {
         if ( < 0)
             throw new IllegalStateException("No match available");
         if (group > groupCount())
             throw new IndexOutOfBoundsException("No group " + group);
         return [group * 2];
     }

    
Returns the offset after the last character matched.

Returns:
The offset after the last character matched
Throws:
java.lang.IllegalStateException If no match has yet been attempted, or if the previous match operation failed
 
     public int end() {
         if ( < 0)
             throw new IllegalStateException("No match available");
         return ;
     }

    
Returns the offset after the last character of the subsequence captured by the given group during the previous match operation.

Capturing groups are indexed from left to right, starting at one. Group zero denotes the entire pattern, so the expression m.end(0) is equivalent to m.end().

Parameters:
group The index of a capturing group in this matcher's pattern
Returns:
The offset after the last character captured by the group, or -1 if the match was successful but the group itself did not match anything
Throws:
java.lang.IllegalStateException If no match has yet been attempted, or if the previous match operation failed
java.lang.IndexOutOfBoundsException If there is no capturing group in the pattern with the given index
 
     public int end(int group) {
         if ( < 0)
             throw new IllegalStateException("No match available");
         if (group > groupCount())
             throw new IndexOutOfBoundsException("No group " + group);
         return [group * 2 + 1];
     }

    
Returns the input subsequence matched by the previous match.

For a matcher m with input sequence s, the expressions m.group() and s.substring(m.start(), m.end()) are equivalent.

Note that some patterns, for example a*, match the empty string. This method will return the empty string when the pattern successfully matches the empty string in the input.

Returns:
The (possibly empty) subsequence matched by the previous match, in string form
Throws:
java.lang.IllegalStateException If no match has yet been attempted, or if the previous match operation failed
 
     public String group() {
         return group(0);
     }

    
Returns the input subsequence captured by the given group during the previous match operation.

For a matcher m, input sequence s, and group index g, the expressions m.group(g) and s.substring(m.start(g), m.end(g)) are equivalent.

Capturing groups are indexed from left to right, starting at one. Group zero denotes the entire pattern, so the expression m.group(0) is equivalent to m.group().

If the match was successful but the group specified failed to match any part of the input sequence, then null is returned. Note that some groups, for example (a*), match the empty string. This method will return the empty string when such a group successfully matches the empty string in the input.

Parameters:
group The index of a capturing group in this matcher's pattern
Returns:
The (possibly empty) subsequence captured by the group during the previous match, or null if the group failed to match part of the input
Throws:
java.lang.IllegalStateException If no match has yet been attempted, or if the previous match operation failed
java.lang.IndexOutOfBoundsException If there is no capturing group in the pattern with the given index
 
     public String group(int group) {
         if ( < 0)
             throw new IllegalStateException("No match found");
         if (group < 0 || group > groupCount())
             throw new IndexOutOfBoundsException("No group " + group);
         if (([group*2] == -1) || ([group*2+1] == -1))
             return null;
         return getSubSequence([group * 2], [group * 2 + 1]).toString();
     }

    
Returns the number of capturing groups in this matcher's pattern.

Group zero denotes the entire pattern by convention. It is not included in this count.

Any non-negative integer smaller than or equal to the value returned by this method is guaranteed to be a valid group index for this matcher.

Returns:
The number of capturing groups in this matcher's pattern
 
     public int groupCount() {
         return . - 1;
     }

    
Attempts to match the entire region against the pattern.

If the match succeeds then more information can be obtained via the start, end, and group methods.

Returns:
true if, and only if, the entire region sequence matches this matcher's pattern
 
     public boolean matches() {
         return match();
     }

    
Attempts to find the next subsequence of the input sequence that matches the pattern.

This method starts at the beginning of this matcher's region, or, if a previous invocation of the method was successful and the matcher has not since been reset, at the first character not matched by the previous match.

If the match succeeds then more information can be obtained via the start, end, and group methods.

Returns:
true if, and only if, a subsequence of the input sequence matches this matcher's pattern
 
     public boolean find() {
         int nextSearchIndex = ;
         if (nextSearchIndex == )
             nextSearchIndex++;
 
         // If next search starts before region, start it at region
         if (nextSearchIndex < )
             nextSearchIndex = ;
 
         // If next search starts beyond region then it fails
         if (nextSearchIndex > ) {
             for (int i = 0; i < .i++)
                 [i] = -1;
             return false;
         }
         return search(nextSearchIndex);
     }

    
Resets this matcher and then attempts to find the next subsequence of the input sequence that matches the pattern, starting at the specified index.

If the match succeeds then more information can be obtained via the start, end, and group methods, and subsequent invocations of the find() method will start at the first character not matched by this match.

Returns:
true if, and only if, a subsequence of the input sequence starting at the given index matches this matcher's pattern
Throws:
java.lang.IndexOutOfBoundsException If start is less than zero or if start is greater than the length of the input sequence.
 
     public boolean find(int start) {
         int limit = getTextLength();
         if ((start < 0) || (start > limit))
             throw new IndexOutOfBoundsException("Illegal start index");
         reset();
         return search(start);
     }

    
Attempts to match the input sequence, starting at the beginning of the region, against the pattern.

Like the matches method, this method always starts at the beginning of the region; unlike that method, it does not require that the entire region be matched.

If the match succeeds then more information can be obtained via the start, end, and group methods.

Returns:
true if, and only if, a prefix of the input sequence matches this matcher's pattern
 
     public boolean lookingAt() {
         return match();
     }

    
Returns a literal replacement String for the specified String. This method produces a String that will work as a literal replacement s in the appendReplacement method of the Matcher class. The String produced will match the sequence of characters in s treated as a literal sequence. Slashes ('\') and dollar signs ('$') will be given no special meaning.

Parameters:
s The string to be literalized
Returns:
A literal string replacement
Since:
1.5
 
     public static String quoteReplacement(String s) {
         if ((s.indexOf('\\') == -1) && (s.indexOf('$') == -1))
             return s;
         StringBuilder sb = new StringBuilder();
         for (int i=0; i<s.length(); i++) {
             char c = s.charAt(i);
             if (c == '\\' || c == '$') {
                 sb.append('\\');
             }
             sb.append(c);
         }
         return sb.toString();
     }

    
Implements a non-terminal append-and-replace step.

This method performs the following actions:

  1. It reads characters from the input sequence, starting at the append position, and appends them to the given string buffer. It stops after reading the last character preceding the previous match, that is, the character at index start() - 1.

  2. It appends the given replacement string to the string buffer.

  3. It sets the append position of this matcher to the index of the last character matched, plus one, that is, to end().

The replacement string may contain references to subsequences captured during the previous match: Each occurrence of $g will be replaced by the result of evaluating group(g). The first number after the $ is always treated as part of the group reference. Subsequent numbers are incorporated into g if they would form a legal group reference. Only the numerals '0' through '9' are considered as potential components of the group reference. If the second group matched the string "foo", for example, then passing the replacement string "$2bar" would cause "foobar" to be appended to the string buffer. A dollar sign ($) may be included as a literal in the replacement string by preceding it with a backslash (\$).

Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.

This method is intended to be used in a loop together with the appendTail and find methods. The following code, for example, writes one dog two dogs in the yard to the standard-output stream:

 Pattern p = Pattern.compile("cat");
 Matcher m = p.matcher("one cat two cats in the yard");
 StringBuffer sb = new StringBuffer();
 while (m.find()) {
     m.appendReplacement(sb, "dog");
 }
 m.appendTail(sb);
 System.out.println(sb.toString());

Parameters:
sb The target string buffer
replacement The replacement string
Returns:
This matcher
Throws:
java.lang.IllegalStateException If no match has yet been attempted, or if the previous match operation failed
java.lang.IndexOutOfBoundsException If the replacement string refers to a capturing group that does not exist in the pattern
 
     public Matcher appendReplacement(StringBuffer sbString replacement) {
 
         // If no match, return error
         if ( < 0)
             throw new IllegalStateException("No match available");
 
         // Process substitution string to replace group references with groups
         int cursor = 0;
         StringBuilder result = new StringBuilder();
 
         while (cursor < replacement.length()) {
             char nextChar = replacement.charAt(cursor);
             if (nextChar == '\\') {
                 cursor++;
                 nextChar = replacement.charAt(cursor);
                 result.append(nextChar);
                 cursor++;
             } else if (nextChar == '$') {
                 // Skip past $
                 cursor++;
                 // The first number is always a group
                 int refNum = (int)replacement.charAt(cursor) - '0';
                 if ((refNum < 0)||(refNum > 9))
                     throw new IllegalArgumentException(
                         "Illegal group reference");
                 cursor++;
 
                 // Capture the largest legal group string
                 boolean done = false;
                 while (!done) {
                     if (cursor >= replacement.length()) {
                         break;
                     }
                     int nextDigit = replacement.charAt(cursor) - '0';
                     if ((nextDigit < 0)||(nextDigit > 9)) { // not a number
                         break;
                     }
                     int newRefNum = (refNum * 10) + nextDigit;
                     if (groupCount() < newRefNum) {
                         done = true;
                     } else {
                         refNum = newRefNum;
                         cursor++;
                     }
                 }
                 // Append group
                 if (start(refNum) != -1 && end(refNum) != -1)
                     result.append(start(refNum), end(refNum));
             } else {
                 result.append(nextChar);
                 cursor++;
             }
         }
         // Append the intervening text
         sb.append();
         // Append the match substitution
         sb.append(result);
 
          = ;
         return this;
     }

    
Implements a terminal append-and-replace step.

This method reads characters from the input sequence, starting at the append position, and appends them to the given string buffer. It is intended to be invoked after one or more invocations of the appendReplacement(java.lang.StringBuffer,java.lang.String) method in order to copy the remainder of the input sequence.

Parameters:
sb The target string buffer
Returns:
The target string buffer
 
     public StringBuffer appendTail(StringBuffer sb) {
         sb.append(getTextLength());
         return sb;
     }

    
Replaces every subsequence of the input sequence that matches the pattern with the given replacement string.

This method first resets this matcher. It then scans the input sequence looking for matches of the pattern. Characters that are not part of any match are appended directly to the result string; each match is replaced in the result by the replacement string. The replacement string may contain references to captured subsequences as in the appendReplacement(java.lang.StringBuffer,java.lang.String) method.

Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.

Given the regular expression a*b, the input "aabfooaabfooabfoob", and the replacement string "-", an invocation of this method on a matcher for that expression would yield the string "-foo-foo-foo-".

Invoking this method changes this matcher's state. If the matcher is to be used in further matching operations then it should first be reset.

Parameters:
replacement The replacement string
Returns:
The string constructed by replacing each matching subsequence by the replacement string, substituting captured subsequences as needed
 
     public String replaceAll(String replacement) {
         reset();
         boolean result = find();
         if (result) {
             StringBuffer sb = new StringBuffer();
             do {
                 appendReplacement(sbreplacement);
                 result = find();
             } while (result);
             appendTail(sb);
             return sb.toString();
         }
         return .toString();
     }

    
Replaces the first subsequence of the input sequence that matches the pattern with the given replacement string.

This method first resets this matcher. It then scans the input sequence looking for a match of the pattern. Characters that are not part of the match are appended directly to the result string; the match is replaced in the result by the replacement string. The replacement string may contain references to captured subsequences as in the appendReplacement(java.lang.StringBuffer,java.lang.String) method.

Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.

Given the regular expression dog, the input "zzzdogzzzdogzzz", and the replacement string "cat", an invocation of this method on a matcher for that expression would yield the string "zzzcatzzzdogzzz".

Invoking this method changes this matcher's state. If the matcher is to be used in further matching operations then it should first be reset.

Parameters:
replacement The replacement string
Returns:
The string constructed by replacing the first matching subsequence by the replacement string, substituting captured subsequences as needed
 
     public String replaceFirst(String replacement) {
         if (replacement == null)
             throw new NullPointerException("replacement");
         reset();
         if (!find())
             return .toString();
         StringBuffer sb = new StringBuffer();
         appendReplacement(sbreplacement);
         appendTail(sb);
         return sb.toString();
     }

    
Sets the limits of this matcher's region. The region is the part of the input sequence that will be searched to find a match. Invoking this method resets the matcher, and then sets the region to start at the index specified by the start parameter and end at the index specified by the end parameter.

Depending on the transparency and anchoring being used (see useTransparentBounds and useAnchoringBounds), certain constructs such as anchors may behave differently at or around the boundaries of the region.

Parameters:
start The index to start searching at (inclusive)
end The index to end searching at (exclusive)
Returns:
this matcher
Throws:
java.lang.IndexOutOfBoundsException If start or end is less than zero, if start is greater than the length of the input sequence, if end is greater than the length of the input sequence, or if start is greater than end.
Since:
1.5
 
     public Matcher region(int startint end) {
         if ((start < 0) || (start > getTextLength()))
             throw new IndexOutOfBoundsException("start");
         if ((end < 0) || (end > getTextLength()))
             throw new IndexOutOfBoundsException("end");
         if (start > end)
             throw new IndexOutOfBoundsException("start > end");
         reset();
          = start;
          = end;
         return this;
     }

    
Reports the start index of this matcher's region. The searches this matcher conducts are limited to finding matches within regionStart (inclusive) and regionEnd (exclusive).

Returns:
The starting point of this matcher's region
Since:
1.5
 
     public int regionStart() {
         return ;
     }

    
Reports the end index (exclusive) of this matcher's region. The searches this matcher conducts are limited to finding matches within regionStart (inclusive) and regionEnd (exclusive).

Returns:
the ending point of this matcher's region
Since:
1.5
 
     public int regionEnd() {
         return ;
     }

    
Queries the transparency of region bounds for this matcher.

This method returns true if this matcher uses transparent bounds, false if it uses opaque bounds.

See useTransparentBounds for a description of transparent and opaque bounds.

By default, a matcher uses opaque region boundaries.

Returns:
true iff this matcher is using transparent bounds, false otherwise.
Since:
1.5
See also:
useTransparentBounds(boolean)
 
     public boolean hasTransparentBounds() {
         return ;
     }

    
Sets the transparency of region bounds for this matcher.

Invoking this method with an argument of true will set this matcher to use transparent bounds. If the boolean argument is false, then opaque bounds will be used.

Using transparent bounds, the boundaries of this matcher's region are transparent to lookahead, lookbehind, and boundary matching constructs. Those constructs can see beyond the boundaries of the region to see if a match is appropriate.

Using opaque bounds, the boundaries of this matcher's region are opaque to lookahead, lookbehind, and boundary matching constructs that may try to see beyond them. Those constructs cannot look past the boundaries so they will fail to match anything outside of the region.

By default, a matcher uses opaque bounds.

Parameters:
b a boolean indicating whether to use opaque or transparent regions
Returns:
this matcher
Since:
1.5
See also:
hasTransparentBounds()
 
     public Matcher useTransparentBounds(boolean b) {
          = b;
         return this;
     }

    
Queries the anchoring of region bounds for this matcher.

This method returns true if this matcher uses anchoring bounds, false otherwise.

See useAnchoringBounds for a description of anchoring bounds.

By default, a matcher uses anchoring region boundaries.

Returns:
true iff this matcher is using anchoring bounds, false otherwise.
Since:
1.5
See also:
useAnchoringBounds(boolean)
    public boolean hasAnchoringBounds() {
        return ;
    }

    
Sets the anchoring of region bounds for this matcher.

Invoking this method with an argument of true will set this matcher to use anchoring bounds. If the boolean argument is false, then non-anchoring bounds will be used.

Using anchoring bounds, the boundaries of this matcher's region match anchors such as ^ and $.

Without anchoring bounds, the boundaries of this matcher's region will not match anchors such as ^ and $.

By default, a matcher uses anchoring region boundaries.

Parameters:
b a boolean indicating whether or not to use anchoring bounds.
Returns:
this matcher
Since:
1.5
See also:
hasAnchoringBounds()
    public Matcher useAnchoringBounds(boolean b) {
         = b;
        return this;
    }

    

Returns the string representation of this matcher. The string representation of a Matcher contains information that may be useful for debugging. The exact format is unspecified.

Returns:
The string representation of this matcher
Since:
1.5
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("java.util.regex.Matcher");
        sb.append("[pattern=" + pattern());
        sb.append(" region=");
        sb.append(regionStart() + "," + regionEnd());
        sb.append(" lastmatch=");
        if (( >= 0) && (group() != null)) {
            sb.append(group());
        }
        sb.append("]");
        return sb.toString();
    }

    

Returns true if the end of input was hit by the search engine in the last match operation performed by this matcher.

When this method returns true, then it is possible that more input would have changed the result of the last search.

Returns:
true iff the end of input was hit in the last match; false otherwise
Since:
1.5
    public boolean hitEnd() {
        return ;
    }

    

Returns true if more input could change a positive match into a negative one.

If this method returns true, and a match was found, then more input could cause the match to be lost. If this method returns false and a match was found, then more input might change the match but the match won't be lost. If a match was not found, then requireEnd has no meaning.

Returns:
true iff more input could change a positive match into a negative one.
Since:
1.5
    public boolean requireEnd() {
        return ;
    }

    
Initiates a search to find a Pattern within the given bounds. The groups are filled with default values and the match of the root of the state machine is called. The state machine will hold the state of the match as it proceeds in this matcher. Matcher.from is not set here, because it is the "hard" boundary of the start of the search which anchors will set to. The from param is the "soft" boundary of the start of the search, meaning that the regex tries to match at that index but ^ won't match there. Subsequent calls to the search methods start at a new "soft" boundary which is the end of the previous match.
    boolean search(int from) {
        this. = false;
        this. = false;
        from        = from < 0 ? 0 : from;
        this.  = from;
        this. =  < 0 ? from : ;
        for (int i = 0; i < .i++)
            [i] = -1;
         = ;
        boolean result = ..match(thisfrom);
        if (!result)
            this. = -1;
        this. = this.;
        return result;
    }

    
Initiates a search for an anchored match to a Pattern within the given bounds. The groups are filled with default values and the match of the root of the state machine is called. The state machine will hold the state of the match as it proceeds in this matcher.
    boolean match(int fromint anchor) {
        this. = false;
        this. = false;
        from        = from < 0 ? 0 : from;
        this.  = from;
        this. =  < 0 ? from : ;
        for (int i = 0; i < .i++)
            [i] = -1;
         = anchor;
        boolean result = ..match(thisfrom);
        if (!result)
            this. = -1;
        this. = this.;
        return result;
    }

    
Returns the end index of the text.

Returns:
the index after the last character in the text
    int getTextLength() {
        return .length();
    }

    
Generates a String from this Matcher's input in the specified range.

Parameters:
beginIndex the beginning index, inclusive
endIndex the ending index, exclusive
Returns:
A String generated from this Matcher's input
    CharSequence getSubSequence(int beginIndexint endIndex) {
        return .subSequence(beginIndexendIndex);
    }

    
Returns this Matcher's input character at index i.

Returns:
A char from the specified index
    char charAt(int i) {
        return .charAt(i);
    }
New to GrepCode? Check out our FAQ X