Arif Arif - 5 months ago 7
Ruby Question

Selectively delete occurrences of a word from a string in Ruby?

For example:

str = "The quick the brown the fox the jumped the over the lazy the dog."


Here, I'd like to know how to do the following two things:


  1. Delete only the third "the"

  2. Delete every third "the"


Answer

As the OP has asked for, the following code:

  • doesn't count "The" as "the".
  • doesn't delete the extra spaces that are left when "the" is deleted.

Using this regex:

re = /((?:\bthe\b.*?){2})\bthe\b/

delete only the third "the":

str.sub(re, '\1')
# => "The quick the brown the fox  jumped the over the lazy the dog."

delete every third "the":

str.gsub(re, '\1')
# => "The quick the brown the fox  jumped the over the lazy  dog."
Comments