Blah Blah
Word1
New line text I need
Another important sentence for me
Word2
Blah blah
Word1
Line of important text
Word2
The end
我需要Word1和Word2之间的所有文字。任何提示?
答案 0 :(得分:9)
您可以使用正则表达式的前瞻和后视功能:
str = <<HERE
Blah Blah
Word1
New line text I need
Another important sentence for me
Word2
Blah blah
Word1
Line of important text
Word2
The end
HERE
str.scan(/(?<=Word1).+?(?=Word2)/m) # => ["\nNew line text I need\nAnother important sentence for me\n", "\nLine of important text\n"]
答案 1 :(得分:1)
假设文本作为键盘输入提供
while gets()
@found=true if line =~ /Word1/
next unless @found
puts line
@found=false if line =~ /Word2/
end
将打印Word1和Word2之间的所有行。