2016-11-16 192 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" 

这样,你可以控制每个元素的而不是完全依赖于正则表达式来做到这一点的一个镜头。