01: /*
02: * $Header: /cvsroot/webman-cms/source/webman/com/teamkonzept/lib/TKSubstitutor.java,v 1.6 2002/01/21 09:53:11 mischa Exp $
03: *
04: */
05: package com.teamkonzept.lib;
06:
07: import com.oroinc.text.regex.*;
08:
09: /**
10: * @author $Author: mischa $
11: * @version $Revision: 1.6 $
12: */
13: public class TKSubstitutor {
14:
15: public String substituteAll(com.oroinc.text.regex.Pattern pat,
16: String text, TKReplaceRule rule) {
17: PatternMatcherInput matcherInput = new PatternMatcherInput(text);
18: PatternMatcher matcher = TKReg.getMatcher();
19:
20: int lastEnd = 0;
21: //int length = 0;
22: boolean noMatch = true;
23: int beginOffset;
24: StringBuffer result = new StringBuffer(text.length());
25: while (matcher.contains(matcherInput, pat)) {
26: MatchResult match = matcher.getMatch();
27: String currSubst = rule.replace(match);
28: if (currSubst != null) {
29: noMatch = false;
30: beginOffset = match.beginOffset(0);
31: if (lastEnd < beginOffset)
32: result.append(text.substring(lastEnd, beginOffset));
33: if (currSubst.length() > 0)
34: result.append(currSubst);
35: lastEnd = match.endOffset(0);
36: }
37: }
38: if (noMatch)
39: return text;
40:
41: return result.append(text.substring(lastEnd)).toString();
42: }
43:
44: public String substituteRecursive(
45: com.oroinc.text.regex.Pattern pat, String text,
46: TKReplaceRule rule) {
47: PatternMatcherInput matcherInput = new PatternMatcherInput(text);
48: PatternMatcher matcher = TKReg.getMatcher();
49:
50: int lastEnd = 0;
51: //int length = 0;
52: boolean noMatch = true;
53: int beginOffset;
54: StringBuffer result = new StringBuffer(text.length());
55: while (matcher.contains(matcherInput, pat)) {
56: MatchResult match = matcher.getMatch();
57: String currSubst = rule.replace(match);
58: if (currSubst != null) {
59: currSubst = substituteRecursive(pat, currSubst, rule);
60: noMatch = false;
61: beginOffset = match.beginOffset(0);
62: if (lastEnd < beginOffset)
63: result.append(text.substring(lastEnd, beginOffset));
64: if (currSubst.length() > 0)
65: result.append(currSubst);
66: lastEnd = match.endOffset(0);
67: }
68: }
69: if (noMatch)
70: return text;
71:
72: return result.append(text.substring(lastEnd)).toString();
73: }
74: }
|