NooB8374 NooB8374 - 1 year ago 71
Ruby Question

Replace word using regular expression in a comma seperated list

I have a comma saparated list : abc, bcd, abc xyz, abc pq
and a word : abc

Help regarding regex to replace the right word in list and covert it to : bcd, abc xyz, abc pq

Answer Source

Comma separated lists can be deconstructed and reconstructed easily:

list = "abc, bcd, abc xyz, abc pq"
list.split(/,\s+/).join(', ')

This means you can delete unwanted elements in the middle:

parts = list.split(/,\s+/)
parts.join(', ')
# => "bcd, abc xyz, abc pq"

A regular expression to do the substitution makes for a lot more work here, but you'll notice I used one to do the separation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download