Dirty Penguin
Dirty Penguin

Reputation: 4402

Perl: Regex matching is unsuccessful

I've tried several different variations of regex, but I still cannot get $found to return results. I've tested these regex on regexterster.com which shows a positive match against the examples in @domains.

I suspect I'm making a very noobish mistake here:

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";
    }
}

Could someone please point out what I'm doing incorrectly?

Upvotes: 0

Views: 78

Answers (2)

ikegami
ikegami

Reputation: 385506

The /i needs to be on the qr//.

I think this can best be explained through example:

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/)

Upvotes: 3

Daniel Gimenez
Daniel Gimenez

Reputation: 20454

Either add the case insensitive modifier or change your expression to:

[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}$

Upvotes: 3

Related Questions