从Ruby中获取字符串中的项目列表

时间:2014-02-12 12:42:51

标签: ruby regex

我有以下字符串,我需要用Ruby解析:

Long description text which could have multiple returns.

This is the final line of the description.
~
1. This is step 1

2. And this is step 2

3. There could be an infinite number of steps

4. But this is the last step

我想把步骤列表中的所有内容拆分成字符串,然后有一系列步骤。

在Objective-C中,我使用范围和while循环执行此操作,直到找不到任何步骤。

我认为Ruby中可能有更聪明的东西,但我找不到任何东西。

1 个答案:

答案 0 :(得分:2)

我会使用splitscan

string = <<EOS
Long description text which could have multiple returns.
This is the final line of the description.
~
1. This is step 1
2. And this is step 2
3. There could be an infinite number of steps
4. But this is the last step
EOS

description, list_text = string.split('~')
list = list_text.scan(/^\d+.*$/)

puts description
# Long description text which could have multiple returns.
# This is the final line of the description.

p list
# ["1. This is step 1", "2. And this is step 2", 
#  "3. There could be an infinite number of steps", 
#  "4. But this is the last step"]