How to add a modifier to a quoted regular expression (qr)

Is there an easy way to add regular expression modifiers like 'i' to the quoted regular expression? For instance:

$pat = qr/F(o+)B(a+)r/; $newpat = $pat . 'i'; # This doesn't work 

The only way I can think of is to print "$pat\n" and return (?-xism:F(o+)B(a+)r) and try to remove the "i" in ?-xism: with replacement

+6
source share
3 answers

You cannot put a flag inside the qr result that you already have, because it is protected. Use this instead:

 $pat = qr/F(o+)B(a+)r/i; 
+6
source

You can modify an existing regular expression as if it were a string, if you recompile it later

  my $pat = qr/F(o+)B(a+)r/; print $pat, "\n"; print 'FOOBAR' =~ $pat ? "match\n" : "mismatch\n"; $pat =~ s/i//; $pat = qr/(?i)$pat/; print $pat, "\n"; print 'FOOBAR' =~ $pat ? "match\n" : "mismatch\n"; 

OUTPUT

  (?-xism:F(o+)B(a+)r) mismatch (?-xism:(?i)(?-xsm:F(o+)B(a+)r)) match 
+2
source

It seems like the only way is to reinforce RE, replace (-i) with (i-), and re-quote it back:

 my $pat = qr/F(o+)B(a+)r/; my $str = "$pat"; $str =~ s/(?<!\\)(\(\?\w*)-([^i:]*)i([^i:]*):/$1i-$2$3:/g; $pati = qr/$str/; 

UPDATE: perl 5.14 quotes regexps in a different way , so my example should look like

 my $pat = qr/F(o+)B(a+)r/; my $str = "$pat"; $str =~ s/(?<!\\)\(\?\^/(?^i/g; $pati = qr/$str/; 

But I do not have perl 5.14 on hand and I can not test it.

UPD2: I also could not check the open bracket.

+1
source

Source: https://habr.com/ru/post/901225/


All Articles