Ruby 多字符串替换
str = "Hello☺ World☹"
预期输出是:
"Hello:) World:("
我可以这样做: str.gsub("☺", ":)").gsub("☹", ":(")
有没有其他方法可以让我在单个函数调用中执行此操作?
str.gsub(['s1', 's2'], ['r1', 'r2'])
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
从 Ruby 1.9.2 开始,
String#gsub
接受哈希值作为第二个参数,以便用匹配的键进行替换。您可以使用正则表达式来匹配需要替换的子字符串,并传递要替换的值的哈希值。像这样:
在 Ruby 1.8.7 中,您可以使用块实现相同的效果:
Since Ruby 1.9.2,
String#gsub
accepts hash as a second parameter for replacement with matched keys. You can use a regular expression to match the substring that needs to be replaced and pass hash for values to be replaced.Like this:
In Ruby 1.8.7, you would achieve the same with a block:
设置映射表:
然后构建正则表达式:
最后,
gsub
:如果你陷入了 1.8 的境地,那么:
你需要
Regexp.escape
以防万一您要替换的任何内容在正则表达式中具有特殊含义。或者,多亏了 steenslag,您可以使用:并且我们会为您处理引用。
Set up a mapping table:
Then build a regex:
And finally,
gsub
:If you're stuck in 1.8 land, then:
You need the
Regexp.escape
in there in case anything you want to replace has a special meaning within a regex. Or, thanks to steenslag, you could use:and the quoting will be take care of for you.
你可以这样做:
可能有一个更有效的解决方案,但这至少使代码更干净一些
You could do something like this:
There may be a more efficient solution, but this at least makes the code a bit cleaner
迟到了,但如果您想用一个字符替换某些字符,您可以使用正则表达式
在本例中,gsub 将下划线 (_)、逗号 (,) 或 ( ) 替换为破折号 (-)
Late to the party but if you wanted to replace certain chars with one, you could use a regex
In this example, gsub is replacing underscores(_), commas (,) or ( ) with a dash (-)
另一种简单但易于阅读的方法如下:
Another simple way, and yet easy to read is the following:
您还可以使用 tr 一次替换字符串中的多个字符,
例如,将“h”替换为“m”,将“l”替换为“t”,
看起来比 gsub 简单、整洁且更快(但没有太大区别)
You can also use tr to replace multiple characters in a string at once,
Eg., replace "h" to "m" and "l" to "t"
looks simple, neat and faster (not much difference though) than gsub
重复上面纳伦的回答,我会选择
所以
'zebraazzeebra'.gsub(/[#{tr.keys}]/, tr)
返回“26e2r112626ee2r1”
Riffing on naren's answer above, I'd go with
So
'zebraazzeebra'.gsub(/[#{tr.keys}]/, tr)
returns"26e2r112626ee2r1"