Sequential Replace

by rfkrocktk
Theory:
Replace
♥0 | Line 47 | Modified 2010-10-07 11:50:48 | MIT License
play

ActionScript3 source code

/**
 * Copyright rfkrocktk ( http://wonderfl.net/user/rfkrocktk )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/sG4R
 */

package {
    import flash.text.TextFormat;
    import flash.text.TextField;
    import flash.display.Sprite;
    
    /**
     * Theory:
     *     Replace 
     */
    public class SequentialReplace extends Sprite {
        
        private var textfield:TextField;
        
        public function SequentialReplace() {
             this.textfield = new TextField();
             this.textfield.x = this.textfield.y = 10;
             this.textfield.width = stage.stageWidth - 20;
             this.textfield.height = stage.stageWidth - 20;
             this.textfield.defaultTextFormat = new TextFormat("Courier New");
             this.addChild(this.textfield);
             
             this.output("Starting Experiment.");
             
             for each (var entry:String in ["yyyy-MM-dd", ">AyyyyA<->MM<->BddB<->"])
                 this.replace(entry);
        }
        
        public function replace(value:String):void {
            this.output("Original String: " + value);
            
            var matchers:Array = [
                { name: "Years Matcher", exp: new RegExp("(y{4})"), value: 2010 },
                { name: "Months Matcher", exp: new RegExp("(M{2})"), value: 10 },
                { name: "Date Matcher", exp: new RegExp("(d{2})"), value: 10 }
            ];
            
            // break the string into chunks
            var chunks:Array = value.split(new RegExp("(y{4}|M{2}|d{2})"));
            
            for (var i:int = 0; i < chunks.length; i++) {
                var chunk:String = chunks[i];
                
                if (chunk == "" || !(new RegExp("(y{4}|M{2}|d{2})").test(chunk)))
                    continue;
                    
                this.output("Found Chunk [" + i + "]: '" + chunk + "'");
                
                var replacement:String = "";
                
                for each (var matcher:Object in matchers) {
                    if (matcher.exp.test(chunk)) {
                        this.output("Chunk " + i + ": Found Matcher - " + matcher.name);
                        replacement = matcher.value.toString();
                        break;
                    }
                }
             
                chunks[i] = replacement;
            }

            
            this.output("Result: " + chunks.join(""));
        }
        
        private function output(message:String):void {
            this.textfield.appendText(message + "\n");
        }
    }
}