如何替换ruby中的每个模式实例?

时间:2009-12-13 01:30:31

标签: ruby regex string replace

string.sub看起来只会替换第一个实例。是否有可以替换所有模式的方法或其他方法?你能在像perl这样的正则表达式中做到吗?

(我觉得像r / blah / blah /)

...和任何可以告诉我为什么在地球上string.sub只替换第一场比赛的人?

2 个答案:

答案 0 :(得分:62)

String.gsub应该可以做到这一点。

引用文档:

  

gsub(pattern, replacement) → new_str

     

返回带有所有出现模式的str的副本   替换第二个参数。该模式通常是一个   正则表达式;如果以字符串形式给出,则任何正则表达式都是元字符   包含将按字面解释,例如\\d将匹配a   反弹后跟d,而不是数字。

答案 1 :(得分:6)

我可以解释为什么sub只是替换模式的第一个匹配,但我认为文档做得更好(从命令行的ri String#sub开始):

str.sub(pattern, replacement)         => new_str
str.sub(pattern) {|match| block }     => new_str

Returns a copy of _str_ with the _first_ occurrence of _pattern_
replaced with either _replacement_ or the value of the block.