您可以在full stops(又名句点)上拆分字符串,但这会创建一个数组,其中每个子字符串在句号之前都有一个元素。例如,如果文档有 100 万个这样的子字符串,那么仅获取第三个子字符串将是一种相当低效的方法。
假设字符串是:
mystring =<<_
Now is the time
for all Rubiests
to come to the
aid of their
bowling team.
Or their frisbee
team. Or their
air guitar team.
Or maybe something
else...
_
您可以采取以下几种方法。
#1 使用正则表达式
r = /
(?: # start a non-capture group
.*?\. # match any character any number of times, lazily, followed by a full stop
){2} # end non-capture group and perform operation twice
\K # forget everything matched before
[^.]* # match everything up to the next full stop
/xm # extended/free-spacing regex definition mode and multiline mode
mystring[r]
#=> " Or their\nair guitar team"
你当然可以写正则表达式:
r = /(?:.*?\.){2}\K[^.]*/m
但扩展的形式使其能够自我记录。
正则表达式引擎将逐步遍历字符串,直到找到匹配项或断定不存在匹配项,然后停止。
#2 假装句号是换行符
首先假设我们正在寻找第三行,而不是第三个子字符串后跟一个句号。我们可以这样写:
mystring.each_line.take(3).last.chomp
# => "to come to the"
Enumerable#take 通过检查由global variable $/ 保存的输入记录分隔符 来确定一行何时结束。默认情况下,$/ 等于换行符。因此我们可以这样做:
irs = $/ # save old value, normally \n
$/ = '.'
mystring.each_line.take(3).last[0..-2]
#=> " Or their\nair guitar team"
那就不要留下脚印:
$/ = irs
这里String#each_line 返回一个枚举器(实际上是一个确定值序列的规则),而不是一个数组。