str = "Hello? World?"
Run Code Online (Sandbox Code Playgroud)
预期产出是:
"Hello:) World:("
Run Code Online (Sandbox Code Playgroud)
我可以做这个: str.gsub("?", ":)").gsub("?", ":(")
有没有其他方法可以在单个函数调用中执行此操作?就像是:
str.gsub(['s1', 's2'], ['r1', 'r2'])
Run Code Online (Sandbox Code Playgroud)
Nar*_*iya 113
从Ruby 1.9.2开始,String#gsub接受hash作为第二个参数,用于替换匹配的键.您可以使用正则表达式来匹配需要替换的子字符串,并为要替换的值传递哈希值.
像这样:
'hello'.gsub(/[eo]/, 'e' => 3, 'o' => '*') #=> "h3ll*"
'(0) 123-123.123'.gsub(/[()-,. ]/, '') #=> "0123123123"
Run Code Online (Sandbox Code Playgroud)
在Ruby 1.8.7中,您将使用块实现相同的功能:
dict = { 'e' => 3, 'o' => '*' }
'hello'.gsub /[eo]/ do |match|
dict[match.to_s]
end #=> "h3ll*"
Run Code Online (Sandbox Code Playgroud)
mu *_*ort 38
设置映射表:
map = {'?' => ':)', '?' => ':(' }
Run Code Online (Sandbox Code Playgroud)
然后构建一个正则表达式:
re = Regexp.new(map.keys.map { |x| Regexp.escape(x) }.join('|'))
Run Code Online (Sandbox Code Playgroud)
最后,gsub:
s = str.gsub(re, map)
Run Code Online (Sandbox Code Playgroud)
如果你被困在1.8土地上,那么:
s = str.gsub(re) { |m| map[m] }
Run Code Online (Sandbox Code Playgroud)
如果Regexp.escape要替换的任何内容在正则表达式中具有特殊含义,则需要使用in.或者,感谢steenslag,您可以使用:
re = Regexp.union(map.keys)
Run Code Online (Sandbox Code Playgroud)
报价将为您服务.
Nat*_*sos 35
你可以这样做:
replacements = [ ["?", ":)"], ["?", ":("] ]
replacements.each {|replacement| str.gsub!(replacement[0], replacement[1])}
Run Code Online (Sandbox Code Playgroud)
可能有一个更有效的解决方案,但这至少使代码更清洁
lsa*_*fie 19
晚会,但如果你想用一个替换某些字符,你可以使用正则表达式
string_to_replace.gsub(/_|,| /, '-')
Run Code Online (Sandbox Code Playgroud)
在这个例子中,gsub用短划线( - )替换下划线(_),逗号(,)或()
小智 7
另一种简单但易于阅读的方法如下:
str = '12 ene 2013'
map = {'ene' => 'jan', 'abr'=>'apr', 'dic'=>'dec'}
map.each {|k,v| str.sub!(k,v)}
puts str # '12 jan 2013'
Run Code Online (Sandbox Code Playgroud)
您还可以使用tr一次替换字符串中的多个字符,
例如,将“ h”替换为“ m”,将“ l”替换为“ t”
"hello".tr("hl", "mt")
=> "metto"
Run Code Online (Sandbox Code Playgroud)
看起来比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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
57262 次 |
| 最近记录: |