Override case sensitive regex in Perl

99封情书 提交于 2020-01-11 05:07:33

问题


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.


回答1:


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;


来源:https://stackoverflow.com/questions/28433854/override-case-sensitive-regex-in-perl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!