NooB8374 NooB8374 - 5 months ago 13
Ruby Question

Remove a word and an associated comma and/or spaces from a string

I am given two strings:

s1 = "abc, bcd, abc xyz, abc pq"
s2 = "abc"

I wish to construct a third string that equals
with the first occurrence of
removed. In addition, if that occurence in
is followed by spaces or by a comma and then spaces, those characters are to be removed as well. Lastly, if that occurrence is at the end of
, the spaces preceding that occurrence are to be removed.

In the example above I wish to produce the string

"bcd, abc xyz, abc pq"

Two more examples:

s2 = "xyz" should produce "abc, bcd, abc abc pq"
s2 = "pq" should produce "bcd, abc xyz, abc"

You may assume that if
, that part of the string will not be immediately preceded or followed by characters other than a comma or space. For example, you don't have to worry about cases such as

s1 = "abc, bedbug, bed"
s2 = "bed"


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.