Regex AS3/正则表达式-替换字符串的段
我对正则表达式一无所知。基本上我想做的是有一个error类,我可以用它来调用errors(显然),它看起来像这样:Regex AS3/正则表达式-替换字符串的段,regex,flash,actionscript-3,replace,Regex,Flash,Actionscript 3,Replace,我对正则表达式一无所知。基本上我想做的是有一个error类,我可以用它来调用errors(显然),它看起来像这样: package avian.framework.errors { public class AvError extends Object { // errors public static const LAYER_WARNING:String = "Warning: {0} is not a valid layer - the de
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);
}
}
}
new AvError(AvError.LAYER_WARNING, targetLayer, this);
我希望能够这样使用LAYER_警告:
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);
}
}
}
new AvError(AvError.LAYER_WARNING, targetLayer, this);
并使输出符合以下内容:
Warning: randomLayer is not a valid layer - the default layer _fallback_ has been used as the container for [object AvChild].
其思想是将{0}
替换为在..params
中解析的第一个参数,{1}
替换为第二个参数,等等
我做了一些研究,我想我已经发现我需要使用以下模式进行搜索:
var pattern:RegExp = /{\d}/;
您可以使用StringUtil
var original:String = "Here is my {0} and my {1}!";
var myStr:String = StringUtil.substitute(original, ['first', 'second']);
使用
RegExp
中的g
标志,可以创建一个包含所有{x}
匹配项的数组,然后循环遍历该数组,并用适当的参数替换每个匹配项
代码:
var mystring:String=“{0}转到了{2}上的{1}”;
函数替换(str:String,…params):String
{
变量模式:RegExp=/{\d}/g;
var-ar:Array=str.match(模式);
变量i:uint=0;
对于(i;i我假设您希望在每个字符串常量中有几个具有不同替换实例({0}、{1}、{2},等等)的静态常量
像这样的东西应该会起作用-抱歉,这是未经测试的:
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);
}
公共函数AvError(错误:字符串,…参数)
{
var replacementArray:Array=err.match(newregexp(“{\\d}”,“g”));
对于(变量i:int=0,i
如果您确实有多个具有不同替换实例的静态常量,您将需要检查传递的…params
的适当匹配量。知道我为什么得到:1120:访问未定义的属性StringUtil。?我甚至添加了import mx.utils.StringUtil,但它仍然不起作用。.尝试使用“import mx.utils;”而不是“mx.utils.StringUtil;”仍然不走运;即使使用import mx.utils.*;我希望您在函数体中使用此代码?对吗?您能在这里发布示例或发邮件给我吗adrian@timeister(点)com&