01: /*
02: * Copyright 2001-2004 The Apache Software Foundation
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: *
16: */
17: package org.tp23.antinstaller.antmod;
18:
19: import java.util.regex.Matcher;
20: import java.util.regex.Pattern;
21:
22: import org.apache.tools.ant.BuildException;
23: import org.apache.tools.ant.util.regexp.Regexp;
24: import org.apache.tools.ant.util.regexp.RegexpUtil;
25:
26: /***
27: * Regular expression implementation using the JDK 1.4 regular expression package
28: */
29: public class Jdk14RegexpRegexp extends Jdk14RegexpMatcher implements
30: Regexp {
31:
32: public Jdk14RegexpRegexp() {
33: super ();
34: }
35:
36: protected int getSubsOptions(int options) {
37: int subsOptions = REPLACE_FIRST;
38: if (RegexpUtil.hasFlag(options, REPLACE_ALL)) {
39: subsOptions = REPLACE_ALL;
40: }
41: return subsOptions;
42: }
43:
44: public String substitute(String input, String argument, int options)
45: throws BuildException {
46: // translate \1 to $(1) so that the Matcher will work
47: StringBuffer subst = new StringBuffer();
48: for (int i = 0; i < argument.length(); i++) {
49: char c = argument.charAt(i);
50: if (c == '$') {
51: subst.append('\\');
52: subst.append('$');
53: } else if (c == '\\') {
54: if (++i < argument.length()) {
55: c = argument.charAt(i);
56: int value = Character.digit(c, 10);
57: if (value > -1) {
58: subst.append("$").append(value);
59: } else {
60: subst.append(c);
61: }
62: } else {
63: // XXX - should throw an exception instead?
64: subst.append('\\');
65: }
66: } else {
67: subst.append(c);
68: }
69: }
70: argument = subst.toString();
71:
72: int sOptions = getSubsOptions(options);
73: Pattern p = getCompiledPattern(options);
74: StringBuffer sb = new StringBuffer();
75:
76: Matcher m = p.matcher(input);
77: if (RegexpUtil.hasFlag(sOptions, REPLACE_ALL)) {
78: sb.append(m.replaceAll(argument));
79: } else {
80: boolean res = m.find();
81: if (res) {
82: m.appendReplacement(sb, argument);
83: m.appendTail(sb);
84: } else {
85: sb.append(input);
86: }
87: }
88:
89: return sb.toString();
90: }
91: }
|