Ruby 多字符串替换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8132492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 04:29:37  来源:igfitidea点击:

Ruby multiple string replacement

rubystringgsub

提问by Sayuj

str = "Hello? World?"

Expected output is:

预期输出为:

"Hello:) World:("

I can do this: str.gsub("?", ":)").gsub("?", ":(")

我可以做这个: str.gsub("?", ":)").gsub("?", ":(")

Is there any other way so that I can do this in a single function call?. Something like:

有没有其他方法可以让我在单个函数调用中做到这一点?就像是:

str.gsub(['s1', 's2'], ['r1', 'r2'])

回答by Naren Sisodiya

Since Ruby 1.9.2, String#gsubaccepts 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.

从 Ruby 1.9.2 开始,String#gsub接受哈希作为第二个参数以替换匹配的键。您可以使用正则表达式来匹配需要替换的子字符串,并为要替换的值传递哈希值。

Like this:

像这样:

'hello'.gsub(/[eo]/, 'e' => 3, 'o' => '*')    #=> "h3ll*"
'(0) 123-123.123'.gsub(/[()-,. ]/, '')    #=> "0123123123"

In Ruby 1.8.7, you would achieve the same with a block:

在 Ruby 1.8.7 中,您可以使用块实现相同的效果:

dict = { 'e' => 3, 'o' => '*' }
'hello'.gsub /[eo]/ do |match|
   dict[match.to_s]
 end #=> "h3ll*"

回答by mu is too short

Set up a mapping table:

建立映射表:

map = {'?' => ':)', '?' => ':(' }

Then build a regex:

然后构建一个正则表达式:

re = Regexp.new(map.keys.map { |x| Regexp.escape(x) }.join('|'))

And finally, gsub:

最后,gsub

s = str.gsub(re, map)

If you're stuck in 1.8 land, then:

如果你被困在 1.8 土地,那么:

s = str.gsub(re) { |m| map[m] }

You need the Regexp.escapein there in case anything you want to replace has a special meaning within a regex. Or, thanks to steenslag, you could use:

如果Regexp.escape您要替换的任何内容在正则表达式中具有特殊含义,则需要在那里。或者,感谢 steenslag,您可以使用:

re = Regexp.union(map.keys)

and the quoting will be take care of for you.

和报价会照顾你。

回答by Nathan Manousos

You could do something like this:

你可以这样做:

replacements = [ ["?", ":)"], ["?", ":("] ]
replacements.each {|replacement| str.gsub!(replacement[0], replacement[1])}

There may be a more efficient solution, but this at least makes the code a bit cleaner

可能有更有效的解决方案,但这至少使代码更清晰

回答by lsaffie

Late to the party but if you wanted to replace certain chars with one, you could use a regex

迟到了,但如果你想用一个替换某些字符,你可以使用正则表达式

string_to_replace.gsub(/_|,| /, '-')

In this example, gsub is replacing underscores(_), commas (,) or ( ) with a dash (-)

在此示例中,gsub 将下划线 (_)、逗号 (,) 或 () 替换为破折号 (-)

回答by YasirAzgar

You can also use tr to replace multiple characters in a string at once,

您还可以使用 tr 一次替换字符串中的多个字符,

Eg., replace "h" to "m" and "l" to "t"

例如,将“h”替换为“m”,将“l”替换为“t”

"hello".tr("hl", "mt")
 => "metto"

looks simple, neat and faster (not much difference though) than gsub

看起来比 gsub 简单、整洁、速度更快(虽然没有太大区别)

puts Benchmark.measure {"hello".tr("hl", "mt") }
  0.000000   0.000000   0.000000 (  0.000007)

puts Benchmark.measure{"hello".gsub(/[hl]/, 'h' => 'm', 'l' => 't') }
  0.000000   0.000000   0.000000 (  0.000021)

回答by Diego Dorado

Another simple way, and yet easy to read is the following:

另一种简单但易于阅读的方法如下:

str = '12 ene 2013'
map = {'ene' => 'jan', 'abr'=>'apr', 'dic'=>'dec'}
map.each {|k,v| str.sub!(k,v)}
puts str # '12 jan 2013'

回答by gitb

Riffing on naren's answer above, I'd go with

上面 naren 的回答嗤之以鼻,我会去

tr = {'a' => '1', 'b' => '2', 'z' => '26'}
mystring.gsub(/[#{tr.keys}]/, tr)

So 'zebraazzeebra'.gsub(/[#{tr.keys}]/, tr)returns "26e2r112626ee2r1"

所以 'zebraazzeebra'.gsub(/[#{tr.keys}]/, tr)返回 “26e2r112626ee2r1”