Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 209
Danny Sullivan Avatar asked Feb 10 '15 14:02

Danny Sullivan


1 Answers

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;
like image 69
ikegami Avatar answered Sep 20 '22 00:09

ikegami