Ruby字符串分区



可能重复:
将字符串拆分为列表,但保留拆分模式

"hello world, I am the universe".partition(/I am/)
    #=> ["hello world, ", "I am", " the universe"]

ruby的输出方式是什么?请记住更复杂的字符串。

#=> ["hello world, ", "I am the universe"]

综合体:

"hello world, I am the universe, I am the world".some_partitioning_function(/I am/)
#=>["hello world, ", "I am the universe, ", "I am the world"]

方法不存在?添加您自己的:

class String
  def some_partitioning_function(delim_str)
    split(delim_str).map.with_index do |str, i|
      i > 0 ? delim_str + str : str
    end
  end
end
"hello world, I am the universe, I am the world".some_partitioning_function('I am')
 => ["hello world, ", "I am the universe, ", "I am the world"] 
"hello world, I am the universe".split(/,s(?=Isam)/,2)

这真的是你想要的吗?

你说这不是@pwned链接到的问题的重复,但有点重复。你只需要稍微摆弄一下Ruby。

s = "hello world, I am the universe, I am the world" # original string
a = s.split(/(I am)/) 
#=> ["hello world, ", "I am", " the universe, ", "I am, " the world"]

现在,我们将使用上面链接的SO问题中建议的解决方案。不过我们将跳过数组的第一个元素。

sliced = a[1..-1].each_slice(2).map(&:join) 
#=> ["I am the universe, ", "I am the world"]

现在我们将其与我们遗漏的数组元素结合起来。

final = [a[0]] + sliced 
#=> ["hello world, ", "I am the universe, ", "I am the world"]

将其放入一个类似于的方法中

class String
  def split_and_include(words)
    s = self.split(/(#{words})/)
    [s[0]] + s[1..-1].each_slice(2).map(&:join)
  end
end 
"You all everybody. You all everybody.".split_and_include("all")
#=> ["You ", "all everybody. You ", "all everybody."]

我相信有一种更干净的方法可以做到这一点,我会在发现一种更简单的方法后更新答案。

我认为这个任务应该用正则表达式来解决,我的正则表达式不太整洁,也许你以后可以修复它。

reg = /(.+?(?=Isam))(Isam.+?(?=Isam)|Isam.+$)/
str = "hello world, I am the universe, I am the world, I am the earth"
str.scan(reg).flatten
=> ["hello world, ", "I am the universe, ", "I am the world, ", "I am the earth"]

最新更新