用于修改 ruby 中的字符串的简化正则表达式
simplified regex for modifying a string in ruby
这是我的原始字符串:
"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",";")
所以我正在寻找一个单衬垫来完成上述操作。因为我不习惯正则表达式,所以我尝试按顺序进行。当我尝试一起做所有这些时,我搞砸了。
替换以下结构
[\n\r]\t(?:\w+: )?
和;
,参见a demo on regex101.com。
我会分几个小步骤来解决它:
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"
这样你就可以控制每个元素,而不是完全依赖于正则表达式来一次性完成。
这是我的原始字符串:
"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",";")
所以我正在寻找一个单衬垫来完成上述操作。因为我不习惯正则表达式,所以我尝试按顺序进行。当我尝试一起做所有这些时,我搞砸了。
替换以下结构
[\n\r]\t(?:\w+: )?
和;
,参见a demo on regex101.com。
我会分几个小步骤来解决它:
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"
这样你就可以控制每个元素,而不是完全依赖于正则表达式来一次性完成。