KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > teamkonzept > lib > TKSubstitutor


1 /*
2  * $Header: /cvsroot/webman-cms/source/webman/com/teamkonzept/lib/TKSubstitutor.java,v 1.6 2002/01/21 09:53:11 mischa Exp $
3  *
4  */

5 package com.teamkonzept.lib;
6
7 import com.oroinc.text.regex.*;
8
9 /**
10  * @author $Author: mischa $
11  * @version $Revision: 1.6 $
12  */

13 public class TKSubstitutor {
14
15     public String JavaDoc substituteAll( com.oroinc.text.regex.Pattern pat, String JavaDoc text, TKReplaceRule rule )
16     {
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 JavaDoc result = new StringBuffer JavaDoc( text.length() );
25         while( matcher.contains( matcherInput, pat ) ) {
26             MatchResult match = matcher.getMatch();
27             String JavaDoc currSubst = rule.replace( match );
28             if( currSubst != null ) {
29                 noMatch = false;
30                 beginOffset = match.beginOffset( 0 );
31                 if( lastEnd < beginOffset ) result.append( text.substring( lastEnd, beginOffset ) );
32                 if( currSubst.length() > 0 ) result.append( currSubst );
33                 lastEnd = match.endOffset( 0 );
34             }
35         }
36         if( noMatch ) return text;
37         
38         return result.append( text.substring( lastEnd ) ).toString();
39     }
40             
41     public String JavaDoc substituteRecursive( com.oroinc.text.regex.Pattern pat, String JavaDoc text, TKReplaceRule rule )
42     {
43         PatternMatcherInput matcherInput = new PatternMatcherInput( text );
44         PatternMatcher matcher = TKReg.getMatcher();
45
46         int lastEnd = 0;
47         //int length = 0;
48
boolean noMatch = true;
49         int beginOffset;
50         StringBuffer JavaDoc result = new StringBuffer JavaDoc( text.length() );
51         while( matcher.contains( matcherInput, pat ) ) {
52             MatchResult match = matcher.getMatch();
53             String JavaDoc currSubst = rule.replace( match );
54             if( currSubst != null ) {
55                 currSubst = substituteRecursive( pat, currSubst, rule );
56                 noMatch = false;
57                 beginOffset = match.beginOffset( 0 );
58                 if( lastEnd < beginOffset ) result.append( text.substring( lastEnd, beginOffset ) );
59                 if( currSubst.length() > 0 ) result.append( currSubst );
60                 lastEnd = match.endOffset( 0 );
61             }
62         }
63         if( noMatch ) return text;
64         
65         return result.append( text.substring( lastEnd ) ).toString();
66     }
67 }
68
69
Popular Tags