Ruby regex - how to replace the nth instance of a match in a string

In my application, I need to find all the substrings of the number, then scan each, find the first that matches the range (for example, between 5 and 15) and replace the THAT instance with another string "X".

My test line s = "1 foo 100 bar 10 gee 1"

My initial pattern is any string of 1 or more digits, for example re = Regexp.new(/\d+/)

matches = s.scan(re) gives ["1", "100", "10", "1"]

If I want to replace the Nth match and only the Nth match, with “X”, how am I?

For example, if I want to replace the third match with “10” (matches [2]), I can't just say s[matches[2]] = "X"because it makes two substitutions

"1 foo X0 bar X gee 1"

Any help would be appreciated!

+5
source share
1 answer

String#gsub , . . :

first = true
"1 foo 100 bar 10 gee 1 12".gsub(/\d+/) do |digits|
  number = digits.to_i
  if number >= 5 && number <= 15 && first
    # do the replacement
    first = false
    'X'
  else
    # don't replace; i.e. replace with itself
    digits
  end
end
# => "1 foo 100 bar X gee 1 12" 
+7

All Articles