示例缓冲区:
1号线是我最喜欢的线 2号线不好 3号线不好 1号线仍然是我最喜欢的线
如何使用正则表达式匹配包含 "Line 1" 的 2 个句子?
请注意,我不知道数字“1”,唯一知道的是多次出现具有相同的数字。
my $s = q{Line 1 is my favourite line
Line 2 is bad
Line 3 is bad
Line 1 is still my favourite line
};
my ($l1, undef, $l2) = $s =~ /(Line \s* ([0-9]+) .*) [\w\W]*? (Line \s* \2 .*)/x;
print "$l1\n$l2\n";
输出
Line 1 is my favourite line
Line 1 is still my favourite line
use 5.14.0; #including features 'say' and smart match (~~)
use warnings;
my @lines = (); #lines that occurred
while (<DATA>){
my $line = /^(Line\s*+\d+\b)/ ? $1 : ''; #\b to avoid '2' matches '22'
$line ~~ @lines and do {say "$line occurred before."; next;};
push @lines, $line;
}
__DATA__
Line 1 is my favourite line
Line 2 is bad
Line 3 is bad
Line 1 is still my favourite line
Line 22 is bad
输出:
Smartmatch is experimental at ./tst.pl line 16.
Line 1 occurred before.
虽然上面的代码可以很好地获取已经发生的行号,但它并没有告诉你这些行是什么。如果您确实想要该功能,请尝试以下代码:
my @lines = ();
while (<DATA>){
my $line = /^(Line\s*+\d+\b)/ ? $1 : ''; #\b to avoid '2' matches '22'
next unless $line;
push @lines, $_;
my @occurred = grep {/$line/} @lines;
@occurred > 1 and print for @occurred;
}
输出:
Line 1 is my favourite line
Line 1 is still my favourite line