简体   繁体   English

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

[英]Regex - All the substrings between delimiters

small problem with easy regex...I have an input and need the text between 2 words. 容易正则表达式的小问题...我有一个输入,需要2个单词之间的文本。 Example of input: 输入示例:

Blah Blah 
Word1 
New line text I need 
Another important sentence for me 
Word2 
Blah blah 
Word1 
Line of important text 
Word2 
The end

And I need all the text between Word1 and Word2..Any tips? 我需要Word1和Word2之间的所有文本。任何提示?

You can use look-ahead and look-behind features of regular expressions: 您可以使用正则表达式的前瞻和后视功能:

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

Assuming the text is fed as keyboard input 假设文本作为键盘输入提供

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

will print all lines between Word1 and Word2 inclusive. 将打印Word1和Word2之间的所有行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM