这里有几种方法可以做到这一点。两者都使用String#gsub 的形式,它接受一个正则表达式作为它的参数并且没有块,返回一个枚举数。这种形式的gsub 只生成正则表达式的匹配;它与字符串替换无关。
str = "how are you to day"
使用包含肯定前瞻的正则表达式
r = /\w+(?=( \w+))/
str.gsub(r).with_object([]) { |s,a| a << s + $1 }
#=> ["how are", "are you", "you to", "to day"]
我已将枚举器 str.gsub(r) 链接到 Enumerator#with_object。当正则表达式包含捕获组时,String#gsub 是String#scan 的便捷替代品。有关它如何处理捕获组的说明,请参阅 String#scan。
我们可以在free-spacing模式中编写正则表达式以使其自文档化。
r = /
\w+ # match >= 1 word characters
(?= # begin a positive lookahead
( \w+) # match a space followed by >= 1 word characters and save
# to capture group 1
) # end positive lookahead
/x # invoke free-spacing regex definition mode
枚举字符串中的连续单词对
enum = str.gsub(/\w+/)
loop.with_object([]) do |_,a|
a << enum.next + ' ' + enum.peek
end
#=> ["how are", "are you", "you to", "to day"]
见Enumerator#next 和Enumerator#peek。在next 返回字符串中的最后一个单词之后,peek 引发了一个StopIteration 异常,该异常由loop 通过跳出循环并返回数组a 来处理。见Kernel#loop。