将字符串数组拆分为字符串数组

时间:2015-12-26 22:37:50

标签: arrays ruby string grouping slice

我正在寻找一种方法来分割这个字符串数组:

["this", "is", "a", "test", ".", "I", "wonder", "if", "I", "can", "parse", "this",
"text", "?", "Without", "any", "errors", "!"]

以标点符号结束的小组:

[
  ["this", "is", "a", "test", "."],
  ["I", "wonder", "if", "I", "can", "parse", "this", "text", "?"],
  ["Without", "any", "errors", "!"]
]

有一种简单的方法可以做到这一点吗?是最理智的迭代数组的方法,将每个索引添加到临时数组,并在找到标点符号时将该临时数组附加到容器数组中?

我在考虑使用slicemap,但我无法弄清楚是否可能。

2 个答案:

答案 0 :(得分:11)

结帐Enumerable#slice_after

x.slice_after { |e| '.?!'.include?(e) }.to_a

答案 1 :(得分:2)

@ndn给出了这个问题的最佳答案,但我会建议另一种可能适用于其他问题的方法。

通常通过在空格或标点符号上分割字符串来获得诸如您给出的数组之类的数组。例如:

s = "this is a test. I wonder if I can parse this text? Without any errors!"
s.scan /\w+|[.?!]/
  #=> ["this", "is", "a", "test", ".", "I", "wonder", "if", "I", "can",
  #    "parse", "this", "text", "?", "Without", "any", "errors", "!"] 

在这种情况下,您可能会发现以其他方式直接操作字符串更方便。例如,您可以先使用String#split和正则表达式将字符串s分解为句子:

r1 = /
     (?<=[.?!]) # match one of the given punctuation characters in capture group 1
     \s*   # match >= 0 whitespace characters to remove spaces
     /x    # extended/free-spacing regex definition mode

a = s.split(r1)
  #=> ["this is a test.", "I wonder if I can parse this text?",
  #    "Without any errors!"] 

然后分开句子:

r2 = /
     \s+       # match >= 1 whitespace characters
     |         # or
     (?=[.?!]) # use a positive lookahead to match a zero-width string
               # followed by one of the punctuation characters
     /x

b = a.map { |s| s.split(r2) }
  #=> [["this", "is", "a", "test", "."],
  #    ["I", "wonder", "if", "I", "can", "parse", "this", "text", "?"],
  #    ["Without", "any", "errors", "!"]]