1 5 package com.teamkonzept.lib; 6 7 import com.oroinc.text.regex.*; 8 9 13 public class TKSubstitutor { 14 15 public String substituteAll( com.oroinc.text.regex.Pattern pat, String text, TKReplaceRule rule ) 16 { 17 PatternMatcherInput matcherInput = new PatternMatcherInput( text ); 18 PatternMatcher matcher = TKReg.getMatcher(); 19 20 int lastEnd = 0; 21 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 ) 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 substituteRecursive( com.oroinc.text.regex.Pattern pat, String text, TKReplaceRule rule ) 42 { 43 PatternMatcherInput matcherInput = new PatternMatcherInput( text ); 44 PatternMatcher matcher = TKReg.getMatcher(); 45 46 int lastEnd = 0; 47 boolean noMatch = true; 49 int beginOffset; 50 StringBuffer result = new StringBuffer ( text.length() ); 51 while( matcher.contains( matcherInput, pat ) ) { 52 MatchResult match = matcher.getMatch(); 53 String 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 |