我正在做一个需要删除单词中额外字母的项目。
如果一封信连续发生三次或更多次,我们将其压缩为一个字母
-Happyyyyyy -> Happy
-awwwsum -> awsum
-cooool -> col
我正在使用Ruby 1.8.7来做到这一点。我该怎么做?
答案 0 :(得分:3)
以下是您的工作方式:
result = subject.gsub(
/(.) # Match a single character, capture it in group 1
\1{2,} # Match the same character 2 or more times, as many as possible/x,
'\1') # Replace with the one captured character
结果:
> subject = "happyyyy daaaaays!!!"
=> "happyyyy daaaaays!!!"
> result = subject.gsub(/(.)\1{2,}/, '\1')
=> "happy days!"