1

我有:

stage.getChildByName("button_1")

button_1

button_2

button_3

button_...

button_15

我可以很容易地创建一个 var XSample 来存储数字,运行语句,增加 +1 XSample 并将 XSample.toString() 与“button_”一起使用

但是事情会稍微复杂一点,所以我需要在 button_ 之后获取所有内容

stage.getChildByName("button_" + everything)
// it could be button_5, button_Ag6, button_0086, button_93 and so on

我怎么能用正则表达式做到这一点?

谢谢

4

1 回答 1

2

用例:

import flash.display.Shape;
import flash.display.Sprite;

var shapeContainer:Sprite = new Sprite();

addChild(shapeContainer);

var shape_1:Shape = new Shape();
shape_1.name = "shape_ONE";

var shape_2:Shape = new Shape();
shape_2.name = "displayObject_TWO";

var shape_3:Shape = new Shape();
shape_3.name = "shape_THREE";

shapeContainer.addChild(shape_1);
shapeContainer.addChild(shape_2);
shapeContainer.addChild(shape_3);

trace(getIndicesWithChildNamePattern("shape_", shapeContainer)); //0, 2

使用 String.indexOf():

function getIndicesWithChildNamePattern(pattern:String, container:DisplayObjectContainer):Vector.<uint>
{
    var indices:Vector.<uint> = new Vector.<uint>();

    for (var i:uint = 0; i < container.numChildren; i++)
    {
        if (container.getChildAt(i).name.indexOf(pattern) != -1)
        {
            indices.push(i);
        }
    }

    return indices;
}

使用正则表达式:

function getIndicesWithChildNamePattern(pattern:String, container:DisplayObjectContainer):Vector.<uint>
{
    var indices:Vector.<uint> = new Vector.<uint>();
    var regExp:RegExp = new RegExp(pattern, "g");

    for (var i:uint = 0; i < container.numChildren; i++)
    {
        if (container.getChildAt(i).name.match(regExp).length)
        {
            indices.push(i);
        }
    }

    return indices;
}
于 2013-02-02T02:47:33.633 回答