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

谁说我不能喝 提交于 2019-12-06 01:59:48

问题


Is there an easy way to add regex modifiers such as 'i' to a quoted regular expression? For example:

$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 get back (?-xism:F(o+)B(a+)r) and try to remove the 'i' in ?-xism: with a substitution


回答1:


You cannot put the flag inside the result of qr that you already have, because it’s protected. Instead, use this:

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



回答2:


You can modify an existing regex as if it was a string as long as you recompile it afterwards

  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



回答3:


Looks like the only way is to stringify the 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 sample should probably look like

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

But I don't have perl 5.14 at hand and can't test it.

UPD2: I also failed to check for escaped opening parenthesis.



来源:https://stackoverflow.com/questions/8082617/how-to-add-a-modifier-to-a-quoted-regular-qr-expression

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