Perl:显示正则表达式,不匹配

时间:2019-01-05 09:12:22

标签: regex perl

我有这个示例代码

C:\Users\xxx\AppData\Local\Continuum\anaconda3\python.exe

$ 1将显示匹配项“亲爱的兄弟”。 有没有办法获得与该字符串匹配的完整regepx?

在这种情况下

#!/usr/bin/perl
use strict;
use warnings;
my $string = "Dear Brother,fgfgfg Test Test2 Soon trthggh";

if ($string =~ /(expr1|expr2|dear.{0,6}(brother|friend)|Soon)/i){print "$1";}

有可能这样做吗?

3 个答案:

答案 0 :(得分:5)

如果您还是使用程序创建正则表达式,则很容易注入适当的(?<...>)序列,然后查看随后匹配的序列。调整您首次发布的程序:

#!/usr/bin/perl
use strict;
use warnings;

my $string = "Dear Brother, fgfgfg Test Test2 Soon trthggh";
my @regexarray = (qr/expr1/, qr/expr2/, qr/dear.{0,6}(brother|friend)/i, qr/Soon/, qr/out.php\?s=(7644|4206|6571|4205)/);
my $i= 0;

my $regexstring = join "|", map {
    my $groupname= sprintf 'group_%d', $i++;
    qr/(?<$groupname>$_)/i
} @regexarray;

if ($string =~ /($regexstring)/i){
    my $match = $1; 
    print "Found <$1>\n";
    print "Matched via ";
    (my $found) = keys %+;
    print "$found => $+{$found}\n" for keys %+;
    $found =~ /(\d+)$/
        or die "Invalid group name '$found'";
    my $index = $1;
    print "Matched via /$regexarray[ $index ]/\n";
}

我已将字符串切换为上面的正则表达式,以使引用和不​​区分大小写变得更加容易。

输出

Found <Dear Brother>
Matched via group_2 => Dear Brother
Matched via /(?^i:dear.{0,6}(brother|friend))/

答案 1 :(得分:2)

我有这个可行的解决方案。但是对于太多的表达式,我认为循环可能会减慢脚本的速度。欢迎提出其他更好的主意,但请不要再告诉我约$ 1或$&。

#!/usr/bin/perl
use strict;
use warnings;


my $string = "Dear Brother, fgfgfg Test Test2 Soon trthggh";
my $regexstring = "expr1|expr2|dear.{0,6}(brother|friend)|Soon|out.php\?s=(7644|4206|6571|4205)";
my @regexarray = ("expr1", "expr2", "dear.{0,6}(brother|friend)", "Soon", "out.php\?s=(7644|4206|6571|4205)");

if ($string =~ /($regexstring)/i){
    my $match = $1; 
    for my $expr (@regexarray){
        print "$expr\n" if ($match =~ /($expr)/i);
    }
}

答案 2 :(得分:-1)

也许您可以使用这种方法:

my $part2 = "(brother|friend)";
my $part1 = "(expr1|expr2|dear.{0,6}$part2|Soon)";

my $string = "Dear Brother,fgfgfg Test Test2 Soon trthggh";
if ($string =~ /$part1/i){print "$part1";}

我不知道更多自动化的方法。也许您必须入侵regex引擎,而不是直接使用Perl。