在Ruby中正则表达式匹配之前插入字符串的好方法

Axl*_*Axl 6 ruby regex

这样做的好方法是什么?似乎我可以使用几种不同方法的组合来实现我想要的东西,但可能有一个更简单的方法我忽略了.例如,PHP函数preg_replace将执行此操作.Ruby中有类似的东西吗?

我打算做的简单例子:

orig_string = "all dogs go to heaven"
string_to_insert = "nice "
regex = /dogs/

end_result = "all nice dogs go to heaven"
Run Code Online (Sandbox Code Playgroud)

Ash*_*tch 12

它可以使用Ruby的"gsub"完成,如下:

http://railsforphp.com/2008/01/17/regular-expressions-in-ruby/#preg_replace

orig_string = "all dogs go to heaven"
end_result = orig_string.gsub(/dogs/, 'nice \\0')
Run Code Online (Sandbox Code Playgroud)