你可以使用正则表达式来完成它.这是我们要搜索的字符串:
s = %{The first line
The second line
The third line
The fourth line
The fifth line
The sixth line
The seventh line
The eight line
The ninth line
The tenth line
}
Run Code Online (Sandbox Code Playgroud)
EOL对我来说是"\n",但对你来说可能是"\ r \n".我会坚持不变:
EOL = '\n'
Run Code Online (Sandbox Code Playgroud)
为了简化正则表达式,我们将仅为"上下文"定义一次模式:
CONTEXT_LINES = 2
CONTEXT = "((?:.*#{EOL}){#{CONTEXT_LINES}})"
Run Code Online (Sandbox Code Playgroud)
我们将搜索包含"第五"字样的任何行.请注意,此正则表达式必须抓取整行,包括行尾,才能使其正常工作:
regexp = /.*fifth.*#{EOL}/
Run Code Online (Sandbox Code Playgroud)
最后,进行搜索并显示结果:
s =~ /^#{CONTEXT}(#{regexp})#{CONTEXT}/
before, match, after = $1, $2, $3
p before # => "The third line\nThe fourth line\n"
p match # => "The fifth line\n"
p after # => "The sixth line\nThe seventh line\n"
Run Code Online (Sandbox Code Playgroud)