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

时间:2022-11-27 19:18:39

small problem with easy regex...I have an input and need the text between 2 words. Example of input:

容易正则表达式的小问题...我有一个输入,需要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

And I need all the text between Word1 and Word2..Any tips?

我需要Word1和Word2之间的所有文本。任何提示?

2 个解决方案

#1


9  

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

#2


1  

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

#1


9  

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

#2


1  

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