gpt4 book ai didi

regex - 在 Perl 中覆盖区分大小写的正则表达式

转载 作者:行者123 更新时间:2023-12-04 14:11:59 33 4
gpt4 key购买 nike

是否可以覆盖 Perl 中先前定义的正则表达式的区分大小写?例如,如果我有以下内容:

my $upper = qr/BLAH/x;
my $lower = qr/$upper/xi;
warn "blah" =~ $lower

我希望第三行打印一个正匹配。

最佳答案

您可以添加 /i到正则表达式如下:

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;
}

但这不会影响 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;

关于regex - 在 Perl 中覆盖区分大小写的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28433854/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com