initial checkin
[org.ibex.nanogoat.git] / src / gnu / regexp / REMatch.java
1 /*
2  *  gnu/regexp/REMatch.java
3  *  Copyright (C) 1998-2001 Wes Biggs
4  *
5  *  This library is free software; you can redistribute it and/or modify
6  *  it under the terms of the GNU Lesser General Public License as published
7  *  by the Free Software Foundation; either version 2.1 of the License, or
8  *  (at your option) any later version.
9  *
10  *  This library is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  *  GNU Lesser General Public License for more details.
14  *
15  *  You should have received a copy of the GNU Lesser General Public License
16  *  along with this program; if not, write to the Free Software
17  *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */
19
20 package gnu.regexp;
21 import java.io.Serializable;
22
23 /**
24  * An instance of this class represents a match
25  * completed by a gnu.regexp matching function. It can be used
26  * to obtain relevant information about the location of a match
27  * or submatch.
28  *
29  * @author <A HREF="mailto:wes@cacas.org">Wes Biggs</A>
30  */
31 public final class REMatch implements Serializable, Cloneable {
32     private String matchedText;
33
34     // These variables are package scope for fast access within the engine
35     int eflags; // execution flags this match was made using
36
37     // Offset in source text where match was tried.  This is zero-based;
38     // the actual position in the source text is given by (offset + anchor).
39     int offset;
40
41     // Anchor position refers to the index into the source input
42     // at which the matching operation began.
43     // This is also useful for the ANCHORINDEX option.
44     int anchor;
45
46     // Package scope; used by RE.
47     int index; // used while matching to mark current match position in input
48     int[] start; // start positions (relative to offset) for each (sub)exp.
49     int[] end;   // end positions for the same
50     REMatch next; // other possibility (to avoid having to use arrays)
51
52     public Object clone() {
53         try {
54             REMatch copy = (REMatch) super.clone();
55             copy.next = null;
56
57             copy.start = (int[]) start.clone();
58             copy.end = (int[]) end.clone();
59
60             return copy;
61         } catch (CloneNotSupportedException e) {
62             throw new Error(); // doesn't happen
63         }
64     }
65
66     void assignFrom(REMatch other) {
67         start = other.start;
68         end = other.end;
69         index = other.index;
70         // need to deep clone?
71         next = other.next;
72     }
73
74     REMatch(int subs, int anchor, int eflags) {
75         start = new int[subs+1];
76         end = new int[subs+1];
77         this.anchor = anchor;
78         this.eflags = eflags;
79         clear(anchor);
80     }
81
82     void finish(CharIndexed text) {
83         start[0] = 0;
84         StringBuffer sb = new StringBuffer();
85         int i;
86         for (i = 0; i < end[0]; i++)
87             sb.append(text.charAt(i));
88         matchedText = sb.toString();
89         for (i = 0; i < start.length; i++) {
90             // If any subexpressions didn't terminate, they don't count
91             // TODO check if this code ever gets hit
92             if ((start[i] == -1) ^ (end[i] == -1)) {
93                 start[i] = -1;
94                 end[i] = -1;
95             }
96         }
97         next = null; // cut off alternates
98     }
99     
100     /** Clears the current match and moves the offset to the new index. */
101     void clear(int index) {
102         offset = index;
103         this.index = 0;
104         for (int i = 0; i < start.length; i++) {
105             start[i] = end[i] = -1;
106         }
107         next = null; // cut off alternates
108     }
109     
110     /**
111      * Returns the string matching the pattern.  This makes it convenient
112      * to write code like the following:
113      * <P>
114      * <code> 
115      * REMatch myMatch = myExpression.getMatch(myString);<br>
116      * if (myMatch != null) System.out.println("Regexp found: "+myMatch);
117      * </code>
118      */
119     public String toString() {
120         return matchedText;
121     }
122     
123     /**
124      * Returns the index within the input text where the match in its entirety
125      * began.
126      */
127     public int getStartIndex() {
128         return offset + start[0];
129     }
130     
131     /**
132      * Returns the index within the input string where the match in
133      * its entirety ends.  The return value is the next position after
134      * the end of the string; therefore, a match created by the
135      * following call:
136      *
137      * <P>
138      * <code>REMatch myMatch = myExpression.getMatch(myString);</code>
139      * <P>
140      * can be viewed (given that myMatch is not null) by creating
141      * <P>
142      * <code>String theMatch = myString.substring(myMatch.getStartIndex(),
143      * myMatch.getEndIndex());</code>
144      * <P>
145      * But you can save yourself that work, since the <code>toString()</code>
146      * method (above) does exactly that for you.  
147      */
148     public int getEndIndex() {
149         return offset + end[0];
150     }
151   
152     /**
153      * Returns the string matching the given subexpression.  The subexpressions
154      * are indexed starting with one, not zero.  That is, the subexpression
155      * identified by the first set of parentheses in a regular expression
156      * could be retrieved from an REMatch by calling match.toString(1).
157      *
158      * @param sub Index of the subexpression.
159      */
160     public String toString(int sub) {
161         if ((sub >= start.length) || (start[sub] == -1)) return "";
162         return (matchedText.substring(start[sub],end[sub]));
163     }
164     
165     /** 
166      * Returns the index within the input string used to generate this match
167      * where subexpression number <i>sub</i> begins, or <code>-1</code> if
168      * the subexpression does not exist.  The initial position is zero.
169      *
170      * @param sub Subexpression index
171      * @deprecated Use getStartIndex(int) instead.
172      */
173     public int getSubStartIndex(int sub) {
174         if (sub >= start.length) return -1;
175         int x = start[sub];
176         return (x == -1) ? x : offset + x;
177     }
178     
179     /** 
180      * Returns the index within the input string used to generate this match
181      * where subexpression number <i>sub</i> begins, or <code>-1</code> if
182      * the subexpression does not exist.  The initial position is zero.
183      *
184      * @param sub Subexpression index
185      * @since gnu.regexp 1.1.0
186      */
187     public int getStartIndex(int sub) {
188         if (sub >= start.length) return -1;
189         int x = start[sub];
190         return (x == -1) ? x : offset + x;
191     }
192   
193     /** 
194      * Returns the index within the input string used to generate this match
195      * where subexpression number <i>sub</i> ends, or <code>-1</code> if
196      * the subexpression does not exist.  The initial position is zero.
197      *
198      * @param sub Subexpression index
199      * @deprecated Use getEndIndex(int) instead
200      */
201     public int getSubEndIndex(int sub) {
202         if (sub >= start.length) return -1;
203         int x = end[sub];
204         return (x == -1) ? x : offset + x;
205     }
206     
207     /** 
208      * Returns the index within the input string used to generate this match
209      * where subexpression number <i>sub</i> ends, or <code>-1</code> if
210      * the subexpression does not exist.  The initial position is zero.
211      *
212      * @param sub Subexpression index
213      */
214     public int getEndIndex(int sub) {
215         if (sub >= start.length) return -1;
216         int x = end[sub];
217         return (x == -1) ? x : offset + x;
218     }
219     
220     /**
221      * Substitute the results of this match to create a new string.
222      * This is patterned after PERL, so the tokens to watch out for are
223      * <code>$0</code> through <code>$9</code>.  <code>$0</code> matches
224      * the full substring matched; <code>$<i>n</i></code> matches
225      * subexpression number <i>n</i>.
226      *
227      * @param input A string consisting of literals and <code>$<i>n</i></code> tokens.
228      */
229     public String substituteInto(String input) {
230         // a la Perl, $0 is whole thing, $1 - $9 are subexpressions
231         StringBuffer output = new StringBuffer();
232         int pos;
233         for (pos = 0; pos < input.length()-1; pos++) {
234             if ((input.charAt(pos) == '$') && (Character.isDigit(input.charAt(pos+1)))) {
235                 int val = Character.digit(input.charAt(++pos),10);
236                 if (val < start.length) {
237                     output.append(toString(val));
238                 } 
239             } else output.append(input.charAt(pos));
240         }
241         if (pos < input.length()) output.append(input.charAt(pos));
242         return output.toString();
243     }
244 }