[英]A good way to insert a string before a regex match in Ruby
有什么好方法可以做到这一点? 似乎我可以使用几种不同方法的组合来实现我想要的,但我可能忽略了一种更简单的方法。 例如,PHP function preg_replace 将执行此操作。 Ruby 有什么类似的吗?
我打算做的简单例子:
orig_string = "all dogs go to heaven"
string_to_insert = "nice "
regex = /dogs/
end_result = "all nice dogs go to heaven"
可以使用 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')
result = subject.gsub(/(?=\bdogs\b)/, 'nice ')
正则表达式检查字符串中的每个 position 是否可以匹配整个单词dogs
,然后将字符串nice
插入那里。
单词边界锚\b
确保我们不会意外匹配hotdogs
等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.