01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * http://www.apache.org/licenses/LICENSE-2.0
10: *
11: * Unless required by applicable law or agreed to in writing, software
12: * distributed under the License is distributed on an "AS IS" BASIS,
13: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: * See the License for the specific language governing permissions and
15: * limitations under the License.
16: *
17: */
18: package org.apache.tools.ant.util.regexp;
19:
20: import java.util.Vector;
21: import org.apache.regexp.RE;
22: import org.apache.tools.ant.BuildException;
23:
24: /***
25: * Regular expression implementation using the Jakarta Regexp package
26: */
27: public class JakartaRegexpRegexp extends JakartaRegexpMatcher implements
28: Regexp {
29:
30: /** Constructor for JakartaRegexpRegexp */
31: public JakartaRegexpRegexp() {
32: super ();
33: }
34:
35: /**
36: * Convert ant regexp substitution option to apache regex options.
37: *
38: * @param options the ant regexp options
39: * @return the apache regex substition options
40: */
41: protected int getSubsOptions(int options) {
42: int subsOptions = RE.REPLACE_FIRSTONLY;
43: if (RegexpUtil.hasFlag(options, REPLACE_ALL)) {
44: subsOptions = RE.REPLACE_ALL;
45: }
46: return subsOptions;
47: }
48:
49: /**
50: * Perform a substitution on the regular expression.
51: * @param input The string to substitute on
52: * @param argument The string which defines the substitution
53: * @param options The list of options for the match and replace.
54: * @return the result of the operation
55: * @throws BuildException on error
56: */
57: public String substitute(String input, String argument, int options)
58: throws BuildException {
59: Vector v = getGroups(input, options);
60:
61: // replace \1 with the corresponding group
62: StringBuffer result = new StringBuffer();
63: for (int i = 0; i < argument.length(); i++) {
64: char c = argument.charAt(i);
65: if (c == '\\') {
66: if (++i < argument.length()) {
67: c = argument.charAt(i);
68: int value = Character.digit(c, 10);
69: if (value > -1) {
70: result.append((String) v.elementAt(value));
71: } else {
72: result.append(c);
73: }
74: } else {
75: // XXX - should throw an exception instead?
76: result.append('\\');
77: }
78: } else {
79: result.append(c);
80: }
81: }
82: argument = result.toString();
83:
84: RE reg = getCompiledPattern(options);
85: int sOptions = getSubsOptions(options);
86: return reg.subst(input, argument, sOptions);
87: }
88: }
|