Danny Sullivan
Danny Sullivan

Reputation: 3844

Override case sensitive regex in Perl

Is it possible to override the case sensitivity of a previously defined regex in Perl? For instance, if I were to have the following:

my $upper = qr/BLAH/x;
my $lower = qr/$upper/xi;
warn "blah" =~ $lower

I'd like the third line to print a positive match.

Upvotes: 7

Views: 616

Answers (1)

ikegami
ikegami

Reputation: 385754

You can add the /i to the regexp as follows:

use re qw( is_regexp regexp_pattern );

sub make_re_case_insensitive {
   my ($re) = @_;

   return "(?i:$re)" if !is_regexp($re);

   my ($pat, $mods) = regexp_pattern($re);
   if ($mods !~ /i/) {
      $re = eval('qr/$pat/'.$mods.'i')
         or die($@);
   }

   return $re;
}

But that won't affect qr/(?-i:BLAH)/.


This is more of a code reuse question, so I don't have to make two very similar regex that test either uppercase or lowercase.

my $pat = 'BLAH';
my $re1 = qr/$pat/x;
my $re2 = qr/$pat/xi;

Upvotes: 9

Related Questions