Override case sensitive regex in Perl

后端 未结 1 1414
终归单人心
终归单人心 2021-01-12 20:28

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;
         


        
相关标签:
1条回答
  • 2021-01-12 21:16

    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;
    
    0 讨论(0)
提交回复
热议问题