Ради интереса, если вы хотите увеличить последнее целое число в любой строке, вы можете сделать это:
str = "I have 3 cats and 41 rabbits"
str.reverse.sub(/\d+/){ |s| (s.reverse.to_i+1).to_s.reverse }.reverse
#=> "I have 3 cats and 42 rabbits"
Это допустимо только в том случае, если вы измените свое регулярное выражение так, чтобы оно соответствовало обратной версии текста.
В общем, вы можете сделать это:
class String
# Replace the last occurrence of a regex in a string.
# As with `sub` you may specify matches in the replacement string,
# or pass a block instead of the replacement string.
# Unlike `sub` the captured sub-expressions will be passed as
# additional parameters to your block.
def rsub!(pattern,replacement=nil)
if n=rindex(pattern)
found=match(pattern,n)
self[n,found[0].length] = if replacement
replacement.gsub(/\\\d+/){ |s| found[s[1..-1].to_i] || s }
else
yield(*found).to_s
end
end
end
def rsub(pattern,replacement=nil,&block)
dup.tap{ |s| s.rsub!(pattern,replacement,&block) }
end
end
str = "I have 3 cats and 41 rabbits"
puts str.rsub(/(?<=\D)(\d+)/,'xx')
#=> I have 3 cats and xx rabbits
puts str.rsub(/(?<=\D)(\d+)/,'-\1-')
#=> I have 3 cats and -41- rabbits
puts str.rsub(/(?<=\D)(\d+)/){ |n| n.to_i+1 }
#=> I have 3 cats and 42 rabbits
Обратите внимание, что (как и в случае rindex
), поскольку поиск по регулярному выражению начинается с конца строки, вам может потребоваться сделать немного большесложное регулярное выражение, чтобы заставить ваш матч быть жадным.