// Uncolored, plain source file:  trans2.java
// trans2.java // <p> // An example file distributed with com.stevesoft.pat // and com.stevesoft.pat.apps // <p> // This software comes without express or implied warranty. // No claim is made about the suitability of this software for // any purpose and neither we nor SteveSoft shall be liable for // damages suffered by the user of this software. import com.stevesoft.pat.*; import java.io.*;
public class trans2 { public static void main(String[] args) { // As in trans.java, we start with a Transformer // that changes the names for the seasons. This // time, however, we want the Transformer to start // working only after the word "on" is encountered // and stop working when the word "off" is encountered. Transformer season_is_on = new Transformer(true); season_is_on.add(new String[] { "s/\\bspring\\b/SUMMER/i", "s/\\bsummer\\b/FALL/i", "s/\\bfall\\b/WINTER/i", "s/\\bwinter\\b/SPRING/i" });
// Now tell the replacement system how to recognize the Transformer. ReplaceRule.define("season_is_on",season_is_on); // Now create a Regex that does nothing but look for the // word "on" and hands over the job of matching and replacing // to the Transformer named "season_is_on" when it succeeds. // The String ${=season_is_on} causes this to happen. Regex season_is_off = Regex.perlCode("s/\\bon\\b/ON${=season_is_on}/"); // Now tell the replacement system how to recognize this Regex. ReplaceRule.define("season_is_off",season_is_off); // We now tell the Transformer how to turn itself off, that is // how to hand the tasks of matching and replacing back to the // Regex season_is_off. season_is_on.add("s/\\boff\\b/OFF${=season_is_off}/"); // Here is some text to replace, we will process it a few // times. String[] s = new String[]{ "", "Right now, things don't change, spring remains spring.", "But after the word 'on' we find that spring becomes", "summer, winter becomes fall and so on.", "We also make everything capitols so that you can see the", "places where the replacement has occured", "with greater ease. Now have a good, spring, summer,", "winter and fall!" };
// Let us now substitute using the Regex. for(int i=0;i<s.length;i++) System.out.println(season_is_off.replaceAll(s[i])); // This didn't quite work the way we wanted, the // replacement reverted to the rule given by season_is_on // at the beginning of each line. This makes sense, // season_is_on should never lose its "identity." If we // wish to not reset to "season_is_on" we can use a Replacer. // The replacer has no real "identity" and will continue // replacing with whatever rule it was last handed through // the ${= ... } system. Replacer rep = season_is_off.getReplacer(); for(int i=0;i<s.length;i++) System.out.println(rep.replaceAll(s[i])); } }