开发者

Regular Expression in Actionscript 3

I need a AS3 regular expression that allows me to find/replace in strings like these:

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>";

to this:

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>";

I want to be able to replace the spaces at the beginning (inside the > <) for other character. It shouldn't affect the number of character at the right of the spaces or the attributes in the value1 definition.


Assuming that there are no "* " sequences in the text blocks, this should work:

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, "**");
}

I can't think of a way to do it in one replace though.


I think the easiest way to accomplish what you need is to use a function in replace() expression.

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);

It's not performance-safe though; if you are using huge blocks of text and/or launching this routine very frequently, you may want to do something more comlicated, but optimized. One optimization technique is reducing the number of arguments of replaceMathod().

p.s. I think this can be done with one replace() expression and without using replaceMethod(). Look at positive lookaheads and noncapturing groups, may be you can figure it out. http://livedocs.adobe.com/flex/3/html/help.html?content=12_Using_Regular_Expressions_09.html

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜