我正在尝试在AS3中创建一个文本解析器,它在[方括号]中查找单词并用另一组单词替换它们。到目前为止,我已经设法创建了实际的RegEx样式,但它不断吐出两个单词 - 一个在括号中,一个没有。同样地,我无法让它连续运行,直到整个句子被解析,结果出来了。
public function parseWords(words):String {
var replacer:String = words;
var finder:RegExp = new RegExp("\\[([a-zA-Z0-9]+)\\]");
var resulter:Object = finder.exec(words);
trace(resulter[0] == "[Rabbit]");
//trace (replacer);
trace (resulter);
return replacer;
}
追踪结果; 真的[兔子],兔子
有什么想法吗?
答案 0 :(得分:1)
这是你想要做的吗?:
功能:
function replaceWords(subject:String, replacementSet:Array):String
{
var out:String = subject;
var matches:Array = subject.match(/\[\w+\]/g);
for(var i:int = 0; i < matches.length; i++)
{
out = out.replace(matches[i], replacementSet[i]);
}
return out;
}
并测试:
var test:String = "This is [some] text [with] search items.";
trace( replaceWords(test, ["updated", "without"]) );
// This is updated text without search items.