如何搜索、递增和替换 Ruby 字符串中的整数子字符串?
我有很多看起来像这样的文档:
foo_1 foo_2
foo_3
bar_1 foo_4 ...
我想通过获取 foo_[X]
的所有实例并将每个实例替换为 foo_[X+1]
来转换它们代码>.在此示例中:
foo_2 foo_3
foo_4
bar_1 foo_5 ...
我可以使用 gsub 和块来执行此操作吗?如果不是,最干净的方法是什么?我真的在寻找一个优雅的解决方案,因为我总是可以暴力破解它,但感觉有一些正则表达式技巧值得学习。
I have a lot of documents that look like this:
foo_1 foo_2
foo_3
bar_1 foo_4 ...
And I want to convert them by taking all instances of foo_[X]
and replacing each of them with foo_[X+1]
. In this example:
foo_2 foo_3
foo_4
bar_1 foo_5 ...
Can I do this with gsub and a block? If not, what's the cleanest approach? I'm really looking for an elegant solution because I can always brute force it, but feel there's some regex trickery worth learning.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我根本不了解 Ruby,但与此类似的东西应该可以工作:
LE:我实际上使它工作: http: //codepad.org/Z5ThOvTr
I don't know Ruby (at all), but something similar to this should work:
LE: I actually made it work: http://codepad.org/Z5ThOvTr
如果您只想更改 foo_ 后面的数字
注意:Look-behinds 仅适用于 Ruby >= 1.9 版本。
If you just want the numbers following foo_ to be changed
Note: Look-behinds will only work in versions or Ruby >= 1.9.
更简单的是使用 .next
所以,你可以像这样简化你的正则表达式和块
Even simpler is just using .next
So, you could simplify your regex and block like so