2012-12-28 22 views
0

我有以下代碼解析此字符串並將其轉換爲對象。由於其中有重複的密鑰,因此我需要爲每個密鑰添加一個遞增的數字。使用正則表達式解析字符串並追加增量數字

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/ 我需要一個遞增的數字追加到任何有「:{」在它的結束。即查看,按鈕,按鈕,圖像等會變成視圖1,出Button1,Button2圖像1,ETC1

+0

解決http://jsfiddle.net/GaX6E/2/ – Rob

+0

如果已解決問題,請將其作爲答案發布。 – nhahtdh

回答

0

解決jsfiddle.net/GaX6E/2

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