Actionscript中的正则表达式3

时间:2011-06-24 17:15:41

标签: regex actionscript-3

我需要一个AS3正则表达式,允许我在这些字符串中查找/替换:

var str1:String = "<value1 att="1"> some text</value1>";
var str2:String = "<value1 att="1" var="a">  some text and more</value1>";
var str3:String = "<value1 att="ok" var="b" def="12">     some text</value1>";

到此:

str1 = "<value1 att="1">*some text</value1>";
str2 = "<value1 att="1" var="a">**some text and more</value1>";
str3 = "<value1 att="ok" var="b" def="12">*****some text</value1>";

我希望能够替换其他字符的开头(在&gt;&lt;内)的空格。它不应该影响空格右侧的字符数或value1定义中的属性。

2 个答案:

答案 0 :(得分:0)

假设文本块中没有“*”序列,这应该有效:

var s:String = "<value1 att='ok' var='b' def='12'>     some text</value1>";

//find all spaces after a tag closing bracket and replace with a *
s = s.replace(/>\s/g, ">*");

//find all spaces after a * and replace it with a *
//keep doing this until no more can be found
while (s.match(/>\*+\s/g).length) {
    s = s.replace(/\*\s/g, "**");
}

我想不出一种方法可以在一个replace中完成。

答案 1 :(得分:0)

我认为最简单的方法就是在replace()表达式中使用函数。

var replaceMethod:Function = function (match:String, tagName:String, tagContent:String, spaces:String, targetText:String, index:int, whole:String) : String
{
    trace("\t", "found", spaces.length,"spaces in tag '"+tagName+"'");
    trace("\t", "matched string:", match);
    // check tag name or whatever you may want
    // do something with found spaces
    var replacement:String = spaces.replace(" ", "*");    
    return "<"+tagName+" "+tagContent+">"+replacement+targetText;
}

var str1:String = '<value1 att="1">    some text</value1>';
var exp:RegExp = /<(\w+)([ >].*?)>(\s+)(some text)/gm;

trace("before:", str1);
str1 = str1.replace(exp, replaceMethod);
trace("after:", str1);

但这不是性能安全的;如果您经常使用大量文本和/或启动此例程,您可能希望做一些更复杂但更优化的事情。一种优化技术是减少replaceMathod()的参数数量。

P.S。我认为这可以使用一个replace()表达式而不使用replaceMethod()来完成。看看积极的前瞻和非捕捉群体,可能你可以搞清楚。 http://livedocs.adobe.com/flex/3/html/help.html?content=12_Using_Regular_Expressions_09.html