使用在文件中多次出现的标记来分割线条

时间:2017-06-06 12:16:23

标签: ruby

我有一个文件,其内容如下:

this is test line 1 
this is testing purpose 
<public>
am inside of public
doing lot of stuffs and priting result here
</public>
<public>
am inside of another public
doing another set of stuffs and priting here
</public>

我想将此文件拆分为三个不同的部分:

  1. 不在任何部分内的行
  2. 第一部分内部的行
  3. 第二部分内部的行
  4. 我尝试使用take_whiledrop_while

    File.open(filename).each_line.take_while do |l|
      !l.include?('</public>')
    end.drop_while do |l|
      !l.include?('<public>')
    end.drop(1))
    

    但它仅提取第一个<public> ... </public>部分。

    我正在寻找更好的解决方案。任何建议都将不胜感激。

1 个答案:

答案 0 :(得分:2)

File.read(filename).split(/<\/?public>/)
                   .map(&:strip)
                   .reject(&:empty?) # [0..2] if the file has a tail
#⇒ [
#   [0] "this is test line 1 \nthis is testing purpose",
#   [1] "am inside of public\ndoing lot of stuffs and priting result here",
#   [2] "am inside of another public\ndoing another set of stuffs and priting here"
# ]