如何使用 Ruby 删除 CSV 字符串的一部分?
我有一个字符串:
"116,118,120,130"
并且希望在执行时删除第一个、最后一个或中间的任何值。
为此,我使用的是:
"116,118,120,130".gsub('118','')
但问题是字符串包含额外的不必要的逗号:
"116,,120,130"
如果我使用
"116,118,120,130".gsub(',116','')
它将删除逗号,但不会匹配字符串中的“116”,因为“前面没有逗号” 116"
如何匹配我要优雅删除的值前面可能有或没有逗号的字符串部分?
谢谢,
I have a string:
"116,118,120,130"
and will want to delete either the first, last or any value in between upon execution.
To to this I was using:
"116,118,120,130".gsub('118','')
but the problem is the string contains an extra unnessesary comma:
"116,,120,130"
and if I use
"116,118,120,130".gsub(',116','')
it will remove the comma, but then won't match "116" in the string as there is no comma in front of "116"
How can I match parts of my string that may or my not have the comma in front of value I am removing elegantly?
Thanks,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
嗯,我可能会尝试一些...
Hmm, I might try something like...
嗯,有两种简单的方法可以做到这一点。首先,您可以使用正则表达式。一个简单的例子:
会做你想做的事。将 118 替换为您要查找的任何值。但如果您正在寻找超过 1 个值,为什么不直接拆分并重新组合它呢。例如
返回“116,120”
Well, there are two easy ways to do this. First, you can use a regular expression. A simple one like:
Will do what you want. With 118 replaced by whatever value you are looking for. But if you are looking for more then 1 value, why not just split and recombine it. For example
Returns "116,120"
如果它是稍微复杂的 CSV 数据(例如,它嵌入了逗号),请使用 csv 标准库模块
If it's slightly more complicated CSV data (e.g. it has embedded commas), use the csv standard library module