ruby - 将字符串拆分为最大字符数的 block 而不打断单词

标签 ruby regex

我想将一个字符串拆分成 block ,每个 block 都在最大字符数内,比如 2000,并且不拆分单词。

我尝试过如下操作:

text.chars.each_slice(2000).map(&:join)

但有时,单词会被拆分。我尝试了一些正则表达式:

text.scan(/.{1,2000}\b|.{1,2000}/).map(&:strip)

来自 this question , 但我不太明白它是如何工作的,它给了我一些不稳定的行为,有时会给出只包含句点的 block 。

任何指点将不胜感激。

最佳答案

代码

def max_groups(str, n)
  arr = []
  pos = 0     
  loop do
    break arr if pos == str.size
    m = str.match(/.{1,#{n}}(?=[ ]|\z)|.{,#{n-1}}[ ]/, pos)
    return nil if m.nil?
    arr << m[0]
    pos += m[0].size
  end
end

示例

str = "Now is the time for all good people to party"
  #    12345678901234567890123456789012345678901234
  #    0         1         2         3         4

max_groups(str, 5)
  #=> nil
max_groups(str, 6)
  #=> ["Now is", " the ", "time ", "for ", "all ", "good ", "people", " to 
max_groups(str, 10)
  #=> ["Now is the", " time for ", "all good ", "people to ", "party"]
max_groups(str, 14)
  #=> ["Now is the ", "time for all ", "good people to", " party"]
max_groups(str, 15)
  #=> ["Now is the time", " for all good ", "people to party"]
max_groups(str, 29)
  #=> ["Now is the time for all good ", "people to party"]
max_groups(str, 43)
  #=> ["Now is the time for all good people to ", "party"]
max_groups(str, 44)
  #=> ["Now is the time for all good people to party"]

str = "How        you do?"
  #    123456789012345678
  #    0         1

max_groups(str, 4)
  #=> ["How ", "    ", "   ", "you ", "do?"]

关于ruby - 将字符串拆分为最大字符数的 block 而不打断单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49087131/

相关文章:

javascript - 添加删除此 JavaScript RegEx 中的前导和尾随空格

javascript - 正则表达式仅匹配错误匹配的数字

php - 如何使用 php preg_split 从字符串中获取除括号之外的所有内容?

php - 相当于 Ruby 中的 openssl_public_encrypt PHP 函数

ruby-on-rails - Rspec:如何修复所需的编码格式版本 4.8; 34.92 给出的错误

ruby - 以特定顺序运行 RSpec 任务

java - @Pattern 正则表达式不检查空值

Ruby 类关系 : How do I use methods and objects from another class?

ruby - 查找字符串中的常见模式并根据模式对它们进行分组

javascript - 用正则表达式替换字符串,即奇怪的结果