1

Here is my original string:

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

and i want the string to be formatted as :

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

so i used following ruby string functions to do it:

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

so i am looking for a one liner to do the above. since i am not used to regex, i tried doing it sequentially. i am messing it up when i try to do all of them together.

2 Answers 2

5

Replace the following construct

[\n\r]\t(?:\w+: )?

with ;, see a demo on regex101.com.

Sign up to request clarification or add additional context in comments.

Comments

4

I'd tackle it as a few smaller steps:

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"

That way you have control over each element instead of being entirely dependent on the regular expression to do it as one shot.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.