// Uncolored, plain source file:  trans3.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 trans3 { public static void main(String[] args) { // As in trans2.java, we start with a Transformer // and a Regex. However, we don't tell the Transformer // specifically about the Regex. Instead, we use a // special replacement rule called POP... // First, declare two objects, a Transformer... 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", // This next rule uses "POP" which hands off the // job of matching and replacing to whatever had // the job before season_is_on. "s/\\off\\b/OFF${POP}/" });
// 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. // This time, however, we will not change the thing that does // the replacing, but push the seas_is_on Transformer onto // a stack. The ${POP} rule above will return control to the // Regex. // The String ${+season_is_on} signifies the season_is_on is // to be pushed on. The String ${=season_is_on}, used in // trans2.java simply replaces the controlling object. Regex season_is_off = Regex.perlCode("s/\\bon\\b/ON${+season_is_on}/"); // 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])); } }