使用gsub时如何限制替换次数? [英] How do I limit the number of replacements when using gsub?

查看:61
本文介绍了使用gsub时如何限制替换次数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何限制Ruby中String#gsub进行替换的次数?

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

在PHP中,使用preg_replace可以很容易地做到这一点,它使用一个用于限制替换的参数,但是我不知道如何在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.

推荐答案

gsub替换所有出现的情况.

gsub replaces all occurences.

您可以尝试String#sub

You can try String#sub

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

这篇关于使用gsub时如何限制替换次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆