public

  • Download Gist
AS3: python-style template strings
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
package
{
public class StringTemplate
{
/**
* Mimics the python template string format, eg:
*
* "blah blah %(varname)s blah blah"
*
* then you pass in a 'dict' of varnames which get
* substituted into the string when run.
*/
public static function parse(str:String, vars:Object):String
{
var re:RegExp = /\%\((\w+)\)s/g;
var match:Object;
while((match=re.exec(str)) !== null) {
if (vars.hasOwnProperty(match[1])) {
str = str.replace(match[0], vars[match[1]]);
}
}
return str;
}
}
}
gistfile1.as
ActionScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
package
{
public class StringTemplate
{
/**
* Mimics the python template string format, eg:
*
* "blah blah %(varname)s blah blah"
*
* then you pass in a 'dict' of varnames which get
* substituted into the string when run.
*/
public static function parse(str:String, vars:Object):String
{
var re:RegExp = /\%\((\w+)\)s/g;
var match:Object;
while((match=re.exec(str)) !== null) {
if (vars.hasOwnProperty(match[1])) {
str = str.replace(match[0], vars[match[1]]);
}
}
return str;
}
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.