Jun 10, 2009

Regex

I did a quick test with making a simpler API for EReg, and it resulted in this simple class, which takes an EReg as a constructor parameter:

class Regex {

    var exp : EReg;
    var str : String;

    public function new( r : EReg ) {
        exp = r;
    }

    public function match( s : String ) {
        str = s;
        return this;
    }

    public function matchedLeft() {
        return exp.matchedLeft();
    }

    public function matchedRight() {
        return exp.matchedRight();
    }

    public function hasNext() {
        return exp.match( str );
    }

    public function next() {
        var match = new Array<String>();
        var i = 0, m = exp.matched( i );
        while( m != null ) {
            match[i] = m;
            m = exp.matched( ++i );
        }
        str = exp.matchedRight();
        return match;
    }

}

It might be used like this:

var r = new Regex( ~/<%(.*?)%>/sm );
for( m in r.match( str ) )
    trace( "Inside tags: " + m[1] + ", Entire match: " + m[0] );

This is just a quick test which seems to work, unfortunately neko seems to like to throw errors around so most of the next() method would have to be wrapped in try{}catch(){} to work in neko I think. And off course looping through the matches like that is not an optimal solution, it should rather be built into EReg and return the targets own implementation arrays if possible (like the match data arrays in JS and AS).

If you think something is missing - fork it and fix it! http://gist.github.com/127421

Comment
About
developing software is fun.
sitting in a pleasant sofa is fun.
combine for double the fun.
Search