有什么好方法可以做到这一点呢?似乎我可以使用几种不同方法的组合来实现我想要的,但我可能忽略了一种更简单的方法。例如,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"
发布于 2011-07-19 14:53:31
它可以使用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')
发布于 2011-07-19 15:02:06
result = subject.gsub(/(?=\bdogs\b)/, 'nice ')
单词边界锚点\b
确保我们不会意外地匹配hotdogs
等。
https://stackoverflow.com/questions/6743275
复制相似问题