2012-12-28 22 views
1

刪除號碼我有一個字符串:正則表達式和Javascript從字符串

str = 'View:{ 
      Name:"View1", 
      Image:{ 
       BackgroundImage:"Image.gif", 
       Position: [0, 0], 
       Width: 320, 
       Height: 480 
      }, 

      Button:{ 
       BackgroundImage:"Button.gif", 
       Transition:"View2", 
       Position: [49, 80], 
       Width: 216, 
       Height: 71 
      }, 

      Button:{ 
       BackgroundImage:"Button2.gif", 
       Position: [65, 217], 
       Width: 188, 
       Height: 134 
      },' 

,我用這個正則表達式來添加「_#」到具有元素「:{」他們

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

的輸出中是

str = 'View_1:{ 
     Name:"View1", 
     Image_2:{ 
      BackgroundImage:"Image.gif", 
      Position: [0, 0], 
      Width: 320, 
      Height: 480 
     }, 

     Button_3:{ 
      BackgroundImage:"Button.gif", 
      Transition:"View2", 
      Position: [49, 80], 
      Width: 216, 
      Height: 71 
     }, 

     Button_4:{ 
      BackgroundImage:"Button2.gif", 
      Position: [65, 217], 
      Width: 188, 
      Height: 134 
     },' 

然後我做了一堆用它的東西,現在我需要從中剝離出「#」。我將如何去除這些'#'

不過關,但我遇到的另一個問題是,第一個正則表達式是從0開始遞增,並給每個元素下一個遞增的數字。我正在努力使每個元素的類型都增加。 像這樣:

str = 'View_1:{ 
     Name:"View1", 
     Image_1:{ 
      BackgroundImage:"Image.gif", 
      Position: [0, 0], 
      Width: 320, 
      Height: 480 
     }, 

     Button_1:{ 
      BackgroundImage:"Button.gif", 
      Transition:"View2", 
      Position: [49, 80], 
      Width: 216, 
      Height: 71 
     }, 

     Button_2:{ 
      BackgroundImage:"Button2.gif", 
      Position: [65, 217], 
      Width: 188, 
      Height: 134 
     },' 

上什麼IM任何輸入做錯了嗎?

+0

你得到一個語法錯誤arent你嗎? – Ibu

+2

爲什麼不修正構建這個無效的JSON對象的東西:)看起來應該是構建一個對象數組。 – epascarello

+0

爲什麼你需要數字獨立增量?你擔心數字用完嗎? :) – Barmar

回答

1

對於第一個問題,只是:{

對於第二種替代_\d+:{,你需要爲每個類型都有一個單獨的計數器。試試這個:

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

我現在正在測試第一個,但第二個只是給'_1'賦值所有這些都沒有增加,這裏是一個演示http://jsfiddle.net/XLMCc/頂部顯示輸出爲一個對象,下面顯示字符串 – Rob

+0

對不起,如果我誤解,但「只是替換'_ \ d +:{'with':{'。我在我提供的代碼中看不到'_ \ d +:{'。 – Rob

+0

好吧,經過一些調試後,我發現你需要使用'/(\ S +): {/ g'在我給你的那個正則表達式中,否則它會匹配上一行的東西,這就是爲什麼它在所有內容中都給你'1'。至於_ _ d +:{',這將匹配如果你用一個空字符串替換它們,將它們刪除。 –