1. /*
  2. * Copyright 2001-2002,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.Vector;
  19. import org.apache.regexp.RE;
  20. import org.apache.tools.ant.BuildException;
  21. /***
  22. * Regular expression implementation using the Jakarta Regexp package
  23. */
  24. public class JakartaRegexpRegexp extends JakartaRegexpMatcher
  25. implements Regexp {
  26. public JakartaRegexpRegexp() {
  27. super();
  28. }
  29. protected int getSubsOptions(int options) {
  30. int subsOptions = RE.REPLACE_FIRSTONLY;
  31. if (RegexpUtil.hasFlag(options, REPLACE_ALL)) {
  32. subsOptions = RE.REPLACE_ALL;
  33. }
  34. return subsOptions;
  35. }
  36. public String substitute(String input, String argument, int options)
  37. throws BuildException {
  38. Vector v = getGroups(input, options);
  39. // replace \1 with the corresponding group
  40. StringBuffer result = new StringBuffer();
  41. for (int i = 0; i < argument.length(); i++) {
  42. char c = argument.charAt(i);
  43. if (c == '\\') {
  44. if (++i < argument.length()) {
  45. c = argument.charAt(i);
  46. int value = Character.digit(c, 10);
  47. if (value > -1) {
  48. result.append((String) v.elementAt(value));
  49. } else {
  50. result.append(c);
  51. }
  52. } else {
  53. // XXX - should throw an exception instead?
  54. result.append('\\');
  55. }
  56. } else {
  57. result.append(c);
  58. }
  59. }
  60. argument = result.toString();
  61. RE reg = getCompiledPattern(options);
  62. int sOptions = getSubsOptions(options);
  63. return reg.subst(input, argument, sOptions);
  64. }
  65. }