Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby Regex-分隔符之间的所有子字符串_Ruby_Regex - Fatal编程技术网

Ruby Regex-分隔符之间的所有子字符串

Ruby Regex-分隔符之间的所有子字符串,ruby,regex,Ruby,Regex,简单正则表达式的小问题…我有一个输入,需要两个单词之间的文本。 输入示例: 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之间的所有文本。有什么提示吗?假设文本作为键盘输入 while gets() @found=true if l

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

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之间的所有文本。有什么提示吗?

假设文本作为键盘输入

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

将打印Word1和Word2之间的所有行。

您可以使用正则表达式的“向前看”和“向后看”功能:

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