开发者

AS3/Regular Expressions - Replacing segments of a string

I have absolutely no knowledge in Regex whatsoever. Basically what I'm trying to do is have an error class that I can use to call errors (obviously) which looks like this:

package avian.framework.errors 
{
    public class AvError extends Object
    {
        // errors
        public static const LAYER_WARNING:String = "Warning: {0} is not a valid layer - the default layer _fallback_ has been used as the container for {1}."开发者_如何转开发;

        /**
         * Constructor
         * Places a warning or error into the output console to assist with misuse of the framework
         * @param err The error to display
         * @param params A list of Objects to use throughout the error message
         */
        public function AvError(err:String, ...params)
        {
            trace(err);
        }
    }
}

What I want to be able to do is use the LAYER_WARNING like this:

new AvError(AvError.LAYER_WARNING, targetLayer, this);

And have the output be something along the lines of:

Warning: randomLayer is not a valid layer - the default layer _fallback_ has been used as the container for [object AvChild].

The idea is to replace {0} with the first parameter parsed in ...params, {1} with the second, etc.


I've done a bit of research and I think I've worked out that I need to search using this pattern:

var pattern:RegExp = /{\d}/;


You can use StringUtil

var original:String = "Here is my {0} and my {1}!";
var myStr:String    = StringUtil.substitute(original, ['first', 'second']);


Using the g flag in RegExp you can create an array containing all of your {x} matches, then loop through this array and replace each of the matches with the appropriate parameter.

Code:

var mystring:String = "{0} went to {1} on {2}";

function replace(str:String, ...params):String
{
    var pattern:RegExp = /{\d}/g;
    var ar:Array = str.match(pattern);

    var i:uint = 0;
    for(i; i<ar.length; i++)
    {
        str = str.split(ar[i]).join(params[i]);
    }

    return str;
}

trace(replace(mystring, "marty", "work", "friday")); // marty went to work on friday


i'm assuming you want to have several static constants with varying replacement instances ({0}, {1}, {2}, etc.) in each string constant.

something like this should work - sorry, it's untested:

public function AvError(err:String, ...params)
{
        var replacementArray:Array = err.match(new RegExp("{\\d}", "g"));

        for (var i:int = 0, i < replacementArray.length, i++)
            err = err.replace(new RegExp(replacementArray[i], "g"), params[i]);

        trace(err);
}

if you do have several static constants with varying replacement instances, you'll want to check for an appropriate matching amount of …params that are passed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜