如何替换特定字符的连续出现?

时间:2011-12-15 20:20:54

标签: ruby-on-rails ruby

我正在尝试进行以下字符串替换:

Something!!!!!!!! something! something!` => `Something! something! something!
Something!!!!..... something! something!` => `Something!. something! something!

如何在Ruby或Rails中指定一个字符来执行此操作?

3 个答案:

答案 0 :(得分:4)

Ruby的String.squeeze是你的朋友:

'Something!!!!..... something! something!'.squeeze('!.')
=> "Something!. something! something!"

答案 1 :(得分:1)

irb(main):011:0> s = "Something!!!!..... something! something!"
=> "Something!!!!..... something! something!"
irb(main):012:0> s.gsub(/(.)\1+/, '\1')
=> "Something!. something! something!"

变为

irb(main):001:0> s = "sweet"
=> "sweet"
irb(main):002:0> c = "."
=> "."
irb(main):003:0> s.gsub(Regexp.new("#{Regexp.escape(c)}{2,}"), c)
=> "sweet"
irb(main):004:0> s = "Something!!!!..... something! something!"
=> "Something!!!!..... something! something!"
irb(main):005:0> s.gsub(Regexp.new("#{Regexp.escape(c)}{2,}"), c)
=> "Something!!!!. something! something!"

答案 2 :(得分:0)

特定角色应该相当直接:

def remove_extra_occurances(string, character)
  string.gsub(/#{Regexp.escape(character)}{2,}/, character)
end

让它适用于任何角色需要一个非常聪明的正则表达式。不得不承认我不确定正则表达式是否足够,或者是否需要循环结构。