1. /*
  2. * Copyright 2001-2004 The Apache Software Foundation
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  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.apache.tools.ant.util.regexp;
  18. import java.util.regex.Matcher;
  19. import java.util.regex.Pattern;
  20. import org.apache.tools.ant.BuildException;
  21. /***
  22. * Regular expression implementation using the JDK 1.4 regular expression package
  23. */
  24. public class Jdk14RegexpRegexp extends Jdk14RegexpMatcher implements Regexp {
  25. public Jdk14RegexpRegexp() {
  26. super();
  27. }
  28. protected int getSubsOptions(int options) {
  29. int subsOptions = REPLACE_FIRST;
  30. if (RegexpUtil.hasFlag(options, REPLACE_ALL)) {
  31. subsOptions = REPLACE_ALL;
  32. }
  33. return subsOptions;
  34. }
  35. public String substitute(String input, String argument, int options)
  36. throws BuildException {
  37. // translate \1 to $(1) so that the Matcher will work
  38. StringBuffer subst = new StringBuffer();
  39. for (int i = 0; i < argument.length(); i++) {
  40. char c = argument.charAt(i);
  41. if (c == '$') {
  42. subst.append('\\');
  43. subst.append('$');
  44. } else if (c == '\\') {
  45. if (++i < argument.length()) {
  46. c = argument.charAt(i);
  47. int value = Character.digit(c, 10);
  48. if (value > -1) {
  49. subst.append("$").append(value);
  50. } else {
  51. subst.append(c);
  52. }
  53. } else {
  54. // XXX - should throw an exception instead?
  55. subst.append('\\');
  56. }
  57. } else {
  58. subst.append(c);
  59. }
  60. }
  61. argument = subst.toString();
  62. int sOptions = getSubsOptions(options);
  63. Pattern p = getCompiledPattern(options);
  64. StringBuffer sb = new StringBuffer();
  65. Matcher m = p.matcher(input);
  66. if (RegexpUtil.hasFlag(sOptions, REPLACE_ALL)) {
  67. sb.append(m.replaceAll(argument));
  68. } else {
  69. boolean res = m.find();
  70. if (res) {
  71. m.appendReplacement(sb, argument);
  72. m.appendTail(sb);
  73. } else {
  74. sb.append(input);
  75. }
  76. }
  77. return sb.toString();
  78. }
  79. }