【问题标题】:Parse a String and Append Incremented Number using regex使用正则表达式解析字符串并附加递增的数字
【发布时间】:2012-12-28 18:10:55
【问题描述】:

我有以下代码来解析这个字符串并将其转换为一个对象。因为里面有重复的键,所以我需要给每个键附加一个递增的数字。

    var str = 'View\n{\n    Name: View1;\n    Image\n    {\n        BackgroundImage: Image.gif;\n        Position: 0, 0;\n        Width: 320;\n        Height: 480;\n    }\n\n    Button\n    {\n        BackgroundImage: Button.gif;\n        Transition: View2;\n        Position: 49, 80;\n        Width: 216;\n        Height: 71;\n    }\n\n    Button\n    {\n        BackgroundImage: Button2.gif;\n        Position: 65, 217;\n        Width: 188;\n        Height: 134;\n    }\n\n    Label\n    {\n        Position: 106, 91;\n        Width: 96;\n        Height: 34;\n        Text: "Button";\n        FontSize: 32;\n        Color: 0.12549, 0.298039, 0.364706, 1;\n    }\n    Scroll\n    {\n        Position: 106, 91;\n        Width: 96;\n        Height: 34;\n        Button{\n            BackgroundImage: Button2.gif;\n            Position: 65, 217;\n            Width: 188;\n            Height: 134;\n        }\n        Button{\n            BackgroundImage: Button2.gif;\n            Position: 65, 217;\n            Width: 188;\n     \n      Height: 134;\n        }\n\n    }\n\n}';

str = str.replace(/(\w+)\s*\{/g, "$1:{"); // add in colon after each named object
str = str.replace(/\}(\s*\w)/g, "},$1"); // add comma before each new named object
str = str.replace(/;/g, ","); // swap out semicolons with commas
str = str.replace(/,(\s+\})/g, "$1"); // get rid of trailing commas
str = str.replace(/([\d\.]+(, [\d\.]+)+)/g, "[$1]"); // create number arrays
str = str.replace(/"/g, ""); // get rid of all double quotes
str = str.replace(/:\s+([^\[\d\{][^,]+)/g, ':"$1"');  // create strings

$("pre").html(str);

在这个工作演示中:http://jsfiddle.net/T59fL/2/ 我需要将一个递增的数字附加到任何结尾有 ':{' 的东西上。即 View、Button、Button、Image 等会变成 View1、Button1、Button2、Image1 等

【问题讨论】:

标签: javascript regex string parsing


【解决方案1】:

解决了 jsfiddle.net/GaX6E/2

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

【讨论】:

    猜你喜欢
    • 2010-12-17
    • 1970-01-01
    • 2015-11-03
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 2014-09-22
    • 2012-12-20
    相关资源
    最近更新 更多