正则表达式 - 分隔符之间的所有子串
问题描述:
简单正则表达式的小问题...我有一个输入,需要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
我需要所有的字1和Word2..Any提示之间的文本?
答
可以使用前瞻,看看隐藏的正则表达式的特点:
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"]
答
假设文本被馈送作为键盘输入
while gets()
@found=true if line =~ /Word1/
next unless @found
puts line
@found=false if line =~ /Word2/
end
将打印字1字2和(含)之间的所有行。
就像一个魅力其他:-)非常感谢! – Droidik