Ruby 多字符串替换

发布于 2024-12-15 07:17:27 字数 267 浏览 3 评论 0 原文

str = "Hello☺ World☹"

预期输出是:

"Hello:) World:("

我可以这样做: str.gsub("☺", ":)").gsub("☹", ":(")

有没有其他方法可以让我在单个函数调用中执行此操作?

str.gsub(['s1', 's2'], ['r1', 'r2'])
str = "Hello☺ World☹"

Expected output is:

"Hello:) World:("

I can do this: 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'])

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

ζ澈沫 2024-12-22 07:17:27

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

像这样:

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

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

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

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:

'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:

dict = { 'e' => 3, 'o' => '*' }
'hello'.gsub /[eo]/ do |match|
   dict[match.to_s]
 end #=> "h3ll*"
蛮可爱 2024-12-22 07:17:27

设置映射表:

map = {'☺' => ':)', '☹' => ':(' }

然后构建正则表达式:

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

最后, gsub

s = str.gsub(re, map)

如果你陷入了 1.8 的境地,那么:

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

你需要 Regexp.escape 以防万一您要替换的任何内容在正则表达式中具有特殊含义。或者,多亏了 steenslag,您可以使用:

re = Regexp.union(map.keys)

并且我们会为您处理引用。

Set up a mapping table:

map = {'☺' => ':)', '☹' => ':(' }

Then build a regex:

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

And finally, gsub:

s = str.gsub(re, map)

If you're stuck in 1.8 land, then:

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

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:

re = Regexp.union(map.keys)

and the quoting will be take care of for you.

一直在等你来 2024-12-22 07:17:27

你可以这样做:

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

可能有一个更有效的解决方案,但这至少使代码更干净一些

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

慵挽 2024-12-22 07:17:27

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

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

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

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 (-)

薄荷港 2024-12-22 07:17:27

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

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

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'
与风相奔跑 2024-12-22 07:17:27

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

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

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

看起来比 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)

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

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

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

looks simple, neat and faster (not much difference though) than 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)
岁月无声 2024-12-22 07:17:27

重复上面纳伦的回答,我会选择

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

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

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

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文