2016-11-16 133 views
1

這裏修改字符串簡化正則表達式是我原來的字符串:在紅寶石

"Chassis ID TLV\n\tMAC: 00:xx:xx:xx:xx:xx\nPort ID TLV\n\tIfname: Ethernet1/3\nTime to Live TLV\n\t120" 

,我想是要格式化的字符串:

"Chassis ID TLV;00:xx:xx:xx:xx:xx\nPort ID TLV;Ethernet1/3\nTime to Live TLV;120" 

所以我用下面的Ruby字符串函數做它:

y = x.gsub(/\t[a-zA-Z\d]+:/,"\t") 
y = y.gsub(/\t /,"\t") 
y = y.gsub("\n\t",";") 

所以我正在尋找一個班輪做上述。因爲我不習慣正則表達式,所以我試着按順序做。當我嘗試將它們全部放在一起時,我正在搞砸它。

回答

4

我會解決它爲一些較小的步驟:

input = "Chassis ID TLV\n\tMAC: 00:xx:xx:xx:xx:xx\nPort ID TLV\n\tIfname: Ethernet1/3\nTime to Live TLV\n\t120" 
input.split(/\n\t?/).map { |s| s.sub(/\A[^:]+\:\s*/, '') }.join(';') 
# => "Chassis ID TLV;00:xx:xx:xx:xx:xx;Port ID TLV;Ethernet1/3;Time to Live TLV;120" 

這樣,你可以控制每個元素的而不是完全依賴於正則表達式來做到這一點的一個鏡頭。