NooB8374 NooB8374 - 5 months ago 14
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


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.