正则表达式 - 分隔符之间的所有子串

时间:2011-11-30 10:40:17

标签: ruby regex

容易正则表达式的小问题...我有一个输入,需要2个单词之间的文本。 输入示例:

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之间的所有文字。任何提示?

2 个答案:

答案 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之间的所有行。