简体   繁体   中英

How do I limit the number of replacements when using gsub?

How do you limit the number of replacements made by String#gsub in Ruby?

In PHP this can be easy done with preg_replace which takes a parameter for limiting replacements, but I can't figure out how to do this in Ruby.

You can create a counter and decrement that within a gsub loop.

str = 'aaaaaaaaaa'
count = 5
p str.gsub(/a/){if count.zero? then $& else count -= 1; 'x' end}
# => "xxxxxaaaaa"

gsub replaces all occurences.

You can try String#sub

http://ruby-doc.org/core/classes/String.html#M001185

str = 'aaaaaaaaaa'
# The following is so that the variable new_string exists in this scope, 
# not just within the block
new_string = str 
5.times do 
  new_string = new_string.sub('a', 'x')
end

You can use the str.split method, which takes a limit, with a join with the replacement:

str = 'aaaaaaaaaa'
n=5
puts str.split(/a/,n+1).join("e")
# eeeeeaaaaa

This works when the replacement string would match the regex since the split is done prior to the replacement:

# use +1 more than desired replacements...
'aaaaaaaaaa'.split(/a/,6).join(' cat ')
" cat  cat  cat  cat  cat aaaaa"

You can also use gsub with a block and count and ternary:

n=4  
'aaaaaaaaaa'.gsub(/a/){|m| (n-=1) >= 0 ? " cat " : m}
" cat  cat  cat  cat aaaaaa"

You can also use the regex index method with a .times loop:

5.times{str[/a/]='e'}
"eeeeeaaaaa"

But you can't use a replacement that matches the regex:

5.times{str[/a/]=" cat "}
# " c c c c cat t t t t aaaaaaaaa"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM