正则表达式中的模式匹配(Perl)

时间:2013-05-08 04:02:43

标签: regex perl

制作一个模式,该模式将匹配$what中当前包含的任何内容的三个连续副本。也就是说,如果$whatfred,则您的模式应与fredfredfred匹配。如果$whatfred|barney,则您的模式应与fredfredbarneybarneyfredfredbarneybarneybarney或许多其他变体相匹配。 (提示:您应该在模式测试程序的顶部设置$what,并使用my $what = 'fred|barney';)等语句

但我对此的解决方案太容易了,所以我假设错了。我的解决方案是:

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


while (<>){
chomp;

if (/fred|barney/ig) {
    print "pattern found! \n";
}
}

它显示我想要的东西。我甚至不必将模式保存在变量中。有人可以帮我解决这个问题吗?或者,如果我正在做/理解问题错误,请告诉我?

2 个答案:

答案 0 :(得分:2)

此示例应清除您的解决方案的错误:

my @tests = qw(xxxfooxx oofoobar bar bax rrrbarrrrr);
my $str = 'foo|bar';

for my $test (@tests) {
    my $match = $test =~ /$str/ig ? 'match' : 'not match';
    print "$test did $match\n";
}

输出

xxxfooxx did match
oofoobar did match
bar did match
bax did not match
rrrbarrrrr did match 

解决方案

#!/usr/bin/perl

use warnings;
use strict;

# notice the example has the `|`. Meaning 
# match "fred" or "barney" 3 times. 
my $str = 'fred|barney';
my @tests = qw(fred fredfredfred barney barneybarneybarny barneyfredbarney);

for my $test (@tests) {
    if( $test =~ /^($str){3}$/ ) {
        print "$test matched!\n";
    } else {
        print "$test did not match!\n";
    }
}

<强>输出

$ ./test.pl
fred did not match!
fredfredfred matched!
barney did not match!
barneybarneybarny did not match!
barneyfredbarney matched!

答案 1 :(得分:1)

use strict;
use warnings;

my $s="barney/fred";
my @ra=split("/", $s);
my $test="barneybarneyfred"; #etc, this will work on all permutations

if ($test =~ /^(?:$ra[0]|$ra[1]){3}$/)
{
    print "Valid\n";
}
else
{
    print "Invalid\n";
}

拆分根据“/”分隔您的字符串。 (?:$ ra [0] | $ ra [1])说组,但不提取,“barney”或“fred”,{3}正好说三个副本。如果案件无关紧要,请在结束“/”后添加i。 ^表示“以...开头”,$表示“以...结尾”。

编辑: 如果您需要格式为barney \ fred,请使用:

my $s="barney\\fred";
my @ra=split(/\\/, $s);

如果您知道匹配将始终在fred和barney上,那么您可以用fred和barney替换$ ra [0],$ ra [1]。