0

有没有办法将正则表达式用于更复杂的分隔符?

truncate(content, :length=>60, :separator=>' ')

检查标准空间作为分隔符('')对我来说是不够的。我的主要目标是检查 \n (enter/a new line),所以如果有人知道该怎么做,请告诉我。

我也很好奇是否有一种方法可以检查更广泛的事物。

编辑: 对不起,更多细节:我希望有一个像 => / \r\n/这样的分隔符,因此在确定省略号的位置时,truncate 方法将在空格和换行符周围分开,但我不能使用正则表达式。看到问题了吗?

4

2 回答 2

1

截断只允许两个可选参数,:omission并且:separator. 您可以通过以下 truncate 代码看到它仅设置为使用字符串 for :separator

# File activesupport/lib/active_support/core_ext/string/filters.rb, line 38
def truncate(length, options = {})
  text = self.dup
  options[:omission] ||= "..."

  length_with_room_for_omission = length - options[:omission].mb_chars.length
  chars = text.mb_chars
  stop = options[:separator] ? (chars.rindex(options[:separator].mb_chars, length_with_room_for_omission) || length_with_room_for_omission) : length_with_room_for_omission

  (chars.length > length ? chars[0...stop] + options[:omission] : text).to_s
end

话虽如此,您应该能够通过以下方式完成您想要实现的目标(如果我正确理解情况)(首先将换行符和诸如此类的东西切换到空格):

truncate(content.gsub(/\s/i, ' '), :length=>60, :separator=>' ')

如果这太简单了,您可能会想出您想要的内容,只需对官方truncate()代码进行相当简单的修改......

于 2012-10-12T23:35:58.530 回答
0

这对我有用:

truncate(content, :length => 60, :separator => '\n')
于 2012-10-12T23:15:47.687 回答