perl - 如何动态创建替换?

标签 perl dynamic substitution

如何动态添加修饰符到替换中?

my $str = 'aaBaabaabaa';
my $mod = 'g';
$str =~ s/b// + $mod;

最佳答案

qr/(?X:).../ 不适用于仅操作修饰符,如 /g

一种可能的方法是:

#!/usr/bin/perl
use strict;
use warnings;

my $str = 'aaBaabaabaa';

print "BEFORE: ${str}\n";

# regex configuration
my $pattern     = '(.)(.)'; # 'b';
my $replacement = '"$2$1"'; # '';
my $mod         = 'ieg';    # 'g';

# extract operation-only modifiers
my $operation_only = qr/([ge])/;
my %special;
$special{$_}++ foreach ($mod =~ /$operation_only/g);
my $mod_filtered;
($mod_filtered = $mod) =~ s/$operation_only//g;

# generate regex
my $regex    = "(?${mod_filtered}:${pattern})";
my $compiled = qr/$regex/;
print "s/ ${regex} -> ${compiled} / ${replacement} / $mod -> ", join('', sort keys %special), "\n";

# execute substitution
my $replacement_code = sub { return $replacement };
for (1..$special{e} // 0) {
    my $recurse = $replacement_code;
    $replacement_code = sub { return eval $recurse->() };
}

if (exists $special{g}) {
    $str =~ s/$compiled/$replacement_code->()/ge;
} else {
    $str =~ s/$compiled/$replacement_code->()/e;
}

print "AFTER:  ${str}\n";

exit 0;

输出:

$ perl dummy.pl
BEFORE: aaBaabaabaa
s/ (?i:(.)(.)) -> (?^:(?i:(.)(.))) / "$2$1" / ieg -> eg
AFTER:  aaaBbaaaaba

关于perl - 如何动态创建替换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54569131/

相关文章:

javascript - 如何在 jQuery Ajax 中发送动态键和值?

c# - 使用 Dapper 绑定(bind)具有附加动态属性的强类型模型

C++ 动态库段错误

Python正则表达式替换部分字符串

perl - 您在 Perl 中使用哪种安全网?

perl - Tomcat 中 CGI 的环境变量

html - IIS 405 用于访问此页面的 HTTP 动词不允许电子邮件

python - 我如何在表达式中使用 Perl 的 s///?

string - 庆典 : Bad Substitution

json - 编码不带引号的 json 数值