2011-11-30 92 views
4

簡單正則表達式的小問題...我有一個輸入,需要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 

我需要所有的字1和Word2..Any提示之間的文本?

回答

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"] 
+0

就像一個魅力其他:-)非常感謝! – Droidik

1

假設文本被饋送作爲鍵盤輸入

while gets() 
    @found=true if line =~ /Word1/ 
    next unless @found 
    puts line 
    @found=false if line =~ /Word2/ 
end 

將打印字1字2和(含)之間的所有行。

相關問題