Perl:正则表达式匹配不成功

时间:2013-07-08 14:26:18

标签: regex perl

我尝试了几种不同的正则表达式,但我仍然无法让$found返回结果。我在regexterster.com上测试了这些正则表达式,它显示了与@domains中的示例的正面匹配。

我怀疑我在这里犯了一个非常错误的错误:

use strict;
use warnings;

my @domains = ('apples.eat-healthy.com', 'seeds.for-parrots.co.nz', 'spam.sender.info');

my $domain_patterns = qr/
    [A-Z0-9-]+\.[A-Z0-9]{3}$|
    [A-Z0-9-]+\.[A-Z0-9]{2}\.[A-Z0-9]{2}$|
    [A-Z0-9-]+\.[A-Z0-9]{4}$
    /x;

foreach my $domain (@domains) {
    if (my ($found) = $domain =~ m/($domain_patterns)/i) {
        print "Found: $found\n";
    }
}

有人可以指出我做错了什么吗?

2 个答案:

答案 0 :(得分:3)

/i需要qr//

我认为最好通过示例来解释:

my $re1 = qr/B/i;
my $re2 = qr/C/;

/A$re1$re2/i

# ABC   matches
# aBC   matches (Because of /i on /A/i)
# AbC   matches (Because of /i on qr/B/i)
# ABc   doesn't match (C must be uppercase because of lack of /i on qr/C/)

答案 1 :(得分:3)

添加不区分大小写的修饰符或将表达式更改为:

[A-Za-z0-9\-]+\.[A-Za-z0-9]{3}$|
[A-Za-z0-9\-]+\.[A-Za-z0-9]{2}\.[A-Za-z0-9]{2}$|
[A-Za-z0-9\-]+\.[A-Za-z0-9]{4}$