如何在 Perl 中的同一行中打印 rex

How to print rexp in same line in Perl

因此,如果我读取了一个包含行的文件,我需要为每一行找到正则表达式。怎么显示呢

例如:文件中有2行:

Line number one has 123 and 456
line number two has 789

并询问用户输入的特定正则表达式 例如:

Enter a reg expression => /\d{3}/

如何获得这样的输出:

Line 1 has 2 match(es) with starting location(s) shown:
123 [20]    456 [28]
Line 2 has 1 match(es) with starting location(s) shown:
789 [20]

我试过:

print "Enter a reg expression => ";
my $rexp = <>; 
chomp $rexp;

if(/($rexp)/){
   print "S1 and location $-[] \n";

或:

my $n = ($line =~ /$rexp/); 
if (/$rexp/){
    for ( my $i = 0;$i<$n; $i++) {
        no strict 'refs';
        print "Match '$i' at position $-[$i] \n";
    }
} else {
    print "No match \n";
}

但是不起作用。 那么如何在同一行中打印出 2 个(或 2 个以上)rexp 匹配值和位置值。谢谢

您可以使用 while 循环和 m//g 获取所有匹配并将它们和位置保存在数组中,然后使用它打印出结果:

#!/usr/bin/env perl
use warnings;
use strict;
use feature qw/say/;

# Hardcoded RE for demonstration purposes
my $re = qr/\d{3}/;

while (<DATA>) {
    my @matches;
    while (/$re/g) {
        push @matches, "$&: [$-[0]]";
    }
    my $count = @matches;
    say "Line $. has $count match(es) with starting location(s) shown:";
    say join("\t", @matches);
}

__DATA__
Line number one has 123 and 456
line number two has 789

产出

Line 1 has 2 match(es) with starting location(s) shown:
123: [20]   456: [28]
Line 2 has 1 match(es) with starting location(s) shown:
789: [20]

当 运行.