Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex - All the substrings between delimiters

Tags:

regex

ruby

small problem with easy regex...I have an input and need the text between 2 words. 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?

like image 421
Droidik Avatar asked Dec 27 '22 10:12

Droidik


2 Answers

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"]
like image 66
Victor Deryagin Avatar answered Jan 14 '23 16:01

Victor Deryagin


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.

like image 20
dexter Avatar answered Jan 14 '23 15:01

dexter