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=