Ruby 将字符串拆分为列表,但保留拆分模式

Ruby 将字符串拆分为列表,但保留拆分模式,ruby,string,split,Ruby,String,Split,目前我正在按模式拆分字符串,如下所示: outcome_array=the_text.split(pattern_to_split_by) 问题是我分割的模式本身总是被忽略 如何使其包含拆分模式本身?如果将模式与组一起使用,它也将在结果中返回模式: irb(main):007:0> "split it here and here okay".split(/ (here) /) => ["split it", "here", "and", "here", "okay"] 编辑附加信

目前我正在按模式拆分字符串,如下所示:

outcome_array=the_text.split(pattern_to_split_by)
问题是我分割的模式本身总是被忽略


如何使其包含拆分模式本身?

如果将模式与组一起使用,它也将在结果中返回模式:

irb(main):007:0> "split it here and here okay".split(/ (here) /)
=> ["split it", "here", "and", "here", "okay"]
编辑附加信息表明,目标是将拆分项目与拆分项目的一半之一合并。我认为有一个简单的方法可以做到这一点,但我不知道,今天也没有时间玩它。因此,在没有聪明的解决方案的情况下,下面是一种暴力的方法。如上所述,使用
split
方法将拆分的项目包括在数组中。然后遍历数组,并将每秒钟的条目(定义为拆分值)与前一个条目合并

s = "split on the word on and include on with previous"
a = s.split(/(on)/)

# iterate through and combine adjacent items together and store
# results in a second array
b = []
a.each_index{ |i|
   b << a[i] if i.even?
   b[b.length - 1] += a[i] if i.odd?
   }

print b

感谢Mark Wilkins的输入,但这里有一段简短的代码:

irb(main):015:0> s = "split on the word on okay?"
=> "split on the word on okay?"
irb(main):016:0> b=[]; s.split(/(on)/).each_slice(2) { |s| b << s.join }; b
=> ["split on", " the word on", " okay?"]
有关说明,请参见下面的折页


这就是它的工作原理。首先,我们在“on”上拆分,但将其用括号括起来,使其成为一个匹配组。当正则表达式中有一个匹配组传递给
split
时,Ruby将在输出中包含该组:

s.split(/(on)/)
# => ["split", "on", "the word", "on", "okay?"
现在我们想用前面的字符串连接“on”的每个实例<代码>每个_片(2)通过一次将两个元素传递到其块来提供帮助。让我们调用
每个片段(2)
来查看结果。由于
每个_slice
在没有块的情况下调用时将返回一个枚举器,因此我们将
应用于_a
枚举器,以便查看枚举器将枚举器覆盖的内容:

s.split(/(on)/).each_slice(2).to_a
# => [["split", "on"], ["the word", "on"], ["okay?"]]
我们快到了。现在我们所要做的就是把单词连在一起。这让我们得到了上面的完整解决方案。我将把它展开成单独的行,以便更容易理解:

b = []
s.split(/(on)/).each_slice(2) do |s|
  b << s.join
end
b
# => ["split on", "the word on" "okay?"]
map
将其输入数组的每个元素传递给块;块的结果成为输出数组中该位置的新元素。在MRI>=1.8.7中,您可以将其进一步缩短为等效值:

s.split(/(on)/).each_slice(2).map(&:join)

您可以使用正则表达式断言来定位分割点,而无需使用任何输入。下面使用一个肯定的look-behind断言在“on”之后拆分:

s = "split on the word on okay?"
s.split(/(?<=on)/)
=> ["split on", " the word on", " okay?"]
对于这样的情况,您可能希望确保“on”不是较大单词的一部分(如“assertion”),并删除拆分处的空白:

"don't split on assertion".split(/(?<=\bon\b)\s*/)
=> ["don't split on", "assertion"]
“断言时不拆分”。拆分(/(?[“断言时不拆分”)]

您想保存两个字符串,拆分的字符串和未拆分的字符串,这就是您要寻找的?您想在哪里包含模式?在字符串内部?我想返回拆分模式。在字符串内部。您能给出输入和输出的示例吗?@Hermann:您为什么会从
中得到
拆分“
?那‘irb(main):007:0>’是什么东西?在这种情况下,我希望将‘here’作为正在拆分的字符串的一部分。@Hermann:它是.Type“irb”在提示下,您可以动态地输入Ruby命令。@Hermann:我不知道要获得该命令的语法。如果您有一个特定的示例,我认为使用适当的正则表达式可能是可行的。但是,只需“迭代”可能更简单在字符串上手工分割它。当我有时间的时候,我必须再考虑它。有趣的问题。+ 1非常好。我喜欢Ruby;它有简洁而易读的语法。@ WayNoNrad较长的解释非常感谢。你可以使用这些组合在中间分裂,例如:“这>”,“”,“”。
s.split(/(on)/).each_slice(2).map(&:join)
s = "split on the word on okay?"
s.split(/(?<=on)/)
=> ["split on", " the word on", " okay?"]
s = "split on the word on okay?"
s.split(/(?=on)/)
=> ["split ", "on the word ", "on okay?"]
"don't split on assertion".split(/(?<=\bon\b)\s*/)
=> ["don't split on", "assertion"]