Ruby截断单词+长文本

时间:2012-06-27 20:36:15

标签: ruby regex truncation

我有以下函数接受文本和字数,如果文本中的字数超过字数,则会用省略号截断。

#Truncate the passed text. Used for headlines and such
  def snippet(thought, wordcount)
    thought.split[0..(wordcount-1)].join(" ") + (thought.split.size > wordcount ? "..." : "")
  end 

然而,这个功能没有考虑到的是非常长的词,例如......

  

“Helloooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo   世界!“

我想知道是否有更好的方法来解决我正在尝试做的事情,因此它会以有效的方式考虑字数和文字大小。

5 个答案:

答案 0 :(得分:4)

这是一个Rails项目吗?

为什么不使用以下帮助器:

truncate("Once upon a time in a world far far away", :length => 17)

如果没有,只需重复使用代码。

答案 1 :(得分:2)

这可能是一个两步过程:

  1. 将字符串截断为最大长度(不需要正则表达式)
  2. 使用正则表达式,从截断的字符串中查找最大单词数量。

  3. 编辑:

    另一种方法是将字符串拆分为单词,循环遍历数组加起来 长度。当您在超限之前发现超限,join 0 .. index

答案 2 :(得分:1)

提示: 正则表达式^(\s*.+?\b){5}将匹配前5个“单词”

答案 3 :(得分:0)

检查单词和字符限制的逻辑变得过于复杂,无法清楚地表达为一个表达式。我会建议这样的事情:

def snippet str, max_words, max_chars, omission='...'
  max_chars = 1+omision.size if max_chars <= omission.size # need at least one char plus ellipses
  words = str.split
  omit = words.size > max_words || str.length > max_chars ? omission : ''
  snip = words[0...max_words].join ' '
  snip = snip[0...(max_chars-3)] if snip.length > max_chars
  snip + omit
end

正如其他人所指出的那样Rails String#truncate几乎提供了你想要的功能(截断以适应自然边界的长度),但它不允许你独立地陈述最大字符长度和字数。

答案 4 :(得分:0)

前20个字符

>> "hello world this is the world".gsub(/.+/) { |m| m[0..20] + (m.size > 20 ? '...' : '') }
=> "hello world this is t..."

前5个字

>> "hello world this is the world".gsub(/.+/) { |m| m.split[0..5].join(' ') + (m.split.size > 5 ? '...' : '') }
=> "hello world this is the world..."