将增量数字添加到字符串使用javascript .replace regex

时间:2013-01-06 17:27:19

标签: javascript regex string auto-increment

我有这个字符串,我试图通过添加_#来增加每个单词/属性,其中#是{左侧增加的数字。

 str = 'View{Image{BackgroundImage: Image.png;Position: 0, 0;Width: 320;Height: 480;}Button{BackgroundImage: ButtonTop.png;Position: 61, 83;Width: 217;Height: 58;}Button_2{BackgroundImage: ButtonBottom.png;Position: 21, 303;Width: 217;Height: 58;}}'

过去我使用过这个正则表达式,但它没有用,我无法弄清楚原因。

var i = {};
str = str.replace(/(\S+):{/g, function (m, p1) {
            i[p1] = (i[p1] || 0) + 1;
            return p1 + "_" + i[p1].toString() + ":{";
        });

期望的输出是:

str = 'View_1{Image_1{BackgroundImage: Image.png;Position: 0, 0;Width: 320;Height: 480;}Button_1{BackgroundImage: ButtonTop.png;Position: 61, 83;Width: 217;Height: 58;}Button_2{BackgroundImage: ButtonBottom.png;Position: 21, 303;Width: 217;Height: 58;}}'

2 个答案:

答案 0 :(得分:1)

根据你的正则表达式,它正在左括号:前面找一个冒号{,它不在你的字符串中。尝试将字符串的开头更改为:

str = 'View:{Image...';

更新:我不确定i变量中包含的是什么 - 它总是一个空对象吗?但是如果你继续增加数字,这个替换函数可能会更适合你(demo):

str = str.replace(/([a-zA-Z]+_?)(\d+)?:{/g, function (m, n, d) {
  d = (parseInt(d,10) || 0) + 1; // add one
  if (!/_$/.test(n)) { n += '_'; } // add _ if name doesn't have it
  return n + d + ":{";
});

答案 1 :(得分:1)

一些小而重要的变化应该让它发挥作用。

首先,我认为str中存在一个小错误。例如,Button_2结尾处str,但我假设您只希望Buttonreplace函数处理递增。否则,结果将是Button_2_1 ...所以我假设您希望str成为:{/ p>

str = 'View{Image{BackgroundImage: Image.png;Position: 0, 0;Width: 320;Height: 480;}Button{BackgroundImage: ButtonTop.png;Position: 61, 83;Width: 217;Height: 58;}Button{BackgroundImage: ButtonBottom.png;Position: 21, 303;Width: 217;Height: 58;}}'

如果那就是这里正确的代码(我希望对你有用),后面有解释:

var i = {};

str = str.replace(/(\w+){/g, function (m, p1) {
    i[p1] = (i[p1] || 0) + 1;
    return p1 + "_" + i[p1].toString() + ":{";
});

在原始代码中,括号中有\S,但这太笼统了,因为它甚至可以捕获大括号{。在正则表达式中,大写\S表示空格的任何字符。小写\w会找到字母数字字符,因此这可能是您要捕获单词ViewImage等的内容。所以现在字符串的任何字母数字部分都直接跟随(没有空格) )通过一个开口大括号将替换为下划线和数字,该数字随该项目的每个实例递增。

我不确定你是否真的希望冒号:出现在每个数字后面,所以我把它留在了,但如果你真的不想要它,只需用return p1 + "_" + i[p1].toString() + "{";替换return语句

否则,如果您对上述(包括冒号)感到满意,则这是结果字符串:

View_1:{Image_1:{BackgroundImage: Image.png;Position: 0, 0;Width: 320;Height: 480;}Button_1:{BackgroundImage: ButtonTop.png;Position: 61, 83;Width: 217;Height: 58;}Button_2:{BackgroundImage: ButtonBottom.png;Position: 21, 303;Width: 217;Height: 58;}}

我认为这就是你想要的。我已经设置了一个小提琴,因此您可以看到更正后的代码in action并进行游戏。

希望这有帮助。