Regex / Perl:匹配两个指定字符串之间的任何字符串的所有实例

时间:2016-11-18 21:56:45

标签: regex string perl

例如,我需要找到“Close”和“Minor”之间出现的所有字符串,但在我的字符串中出现“Close”和“Minor”字样多次。如何使用正则表达式查找“​​Close”和“Minor”的每个实例之间的所有字符串。例如:

在文中

$string = "Minor fall major fifth Close to home Minors cannot vote before 18 Polls Close at 8";

我想匹配

 fall major fifth

s cannot vote before 18 Polls

我试过用这个:

my @matches = $string =~ /Minor(.*) Close/gi;

但匹配

Minor fall major fifth Close to home Minors cannot vote before 18 Polls Close

匹配单词本身,并且不会产生所需的匹配。

我迷路了!

1 个答案:

答案 0 :(得分:1)

使用非贪婪的量词:

use strict;
use warnings;
use v5.10;

my $string = "Minor fall major fifth Close to home Minors cannot vote before 18 Polls Close at 8";

my @matches = $string =~ /Minor(.*?) Close/gi;

say for @matches;

输出:

 fall major fifth
s cannot vote before 18 Polls