Perl中正则表达式的双重插值

tom*_*dee 7 regex perl interpolation

我有一个Perl程序,它在配置文件中存储正则表达式.它们的形式如下:

regex = ^/d+$
Run Code Online (Sandbox Code Playgroud)

在其他地方,正则表达式从文件中解析并存储在变量中 - $regex.然后我在检查正则表达式时使用变量,例如

$lValid = ($valuetocheck =~ /$regex/);
Run Code Online (Sandbox Code Playgroud)

我希望能够在配置文件中包含perl变量,例如

regex = ^\d+$stored_regex$
Run Code Online (Sandbox Code Playgroud)

但我无法弄清楚如何做到这一点.

当Perl解析正则表达式时,它们会被解释两次.首先扩展变量,然后解析正则表达式本身.

我需要的是一个三阶段过程:首先插入$regex,然后插入它包含的变量,然后解析生成的正则表达式.前两个插值都需要"正则表达式识别".例如,他们应该知道字符串包含$锚等...

有任何想法吗?

Leo*_*ans 7

您可以在配置文件中定义regexp,如下所示:

regex = ^\d+(??{$stored_regex})$
Run Code Online (Sandbox Code Playgroud)

但是,您需要在Perl程序中执行此操作时禁用正在使用regexp的块中的安全检查:

use re 'eval';
Run Code Online (Sandbox Code Playgroud)


pot*_*tyl 3

使用eval可以帮助你。看一下下面的代码,它可以预编译一个正则表达式,供以后使用:

my $compiled_regexp;
my $regexp = '^\d+$stored_regexp$';
my $stored_regexp = 'a';

eval "\$compiled_regexp = qr/$regexp/;";
print "$compiled_regexp\n";
Run Code Online (Sandbox Code Playgroud)

运算符 qr// 可用于预编译正则表达式。它允许您构建它但尚未执行它。您可以先用它构建您的正则表达式,然后再使用它们。