Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex Perl中正则表达式的双重插值_Regex_Perl_Interpolation - Fatal编程技术网

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

Regex Perl中正则表达式的双重插值,regex,perl,interpolation,Regex,Perl,Interpolation,我有一个在配置文件中存储正则表达式的Perl程序。它们的形式如下: regex = ^/d+$ 在其他地方,正则表达式从文件中解析并存储在变量-$regex中。 然后在检查正则表达式时使用变量,例如 $lValid = ($valuetocheck =~ /$regex/); 我希望能够在配置文件中包含perl变量,例如 regex = ^\d+$stored_regex$ 但我不知道怎么做 当Perl解析正则表达式时,它们会被解释两次。 首先展开变量,然后解析正则表达式本身 我需要的是一

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

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

$lValid = ($valuetocheck =~ /$regex/);
我希望能够在配置文件中包含perl变量,例如

regex = ^\d+$stored_regex$
但我不知道怎么做

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

我需要的是一个三阶段的过程: 首先插值
$regex
,然后插值它包含的变量,然后解析得到的正则表达式。 前两个插值都需要“正则表达式感知”。e、 g.他们应该知道字符串包含
$
作为锚点等

有什么想法吗?

在这里使用可以帮助您。看一看下面的代码,它可以预编译一个可以在以后使用的regexp:

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

eval "\$compiled_regexp = qr/$regexp/;";
print "$compiled_regexp\n";

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

您的Perl变量不在配置文件的范围内,我认为这是一件好事。埃瓦尔很可怕

您最好实现自己的模板

因此,在配置文件中:

regex = ^\d+__TEMPLATE_FIELD__$
在配置文件读取器中:

# something like this for every template field you need
$regex =~ s/__TEMPLATE_FIELD__/$stored_regex/g;
使用时:

$lValid = ($valuetocheck =~ m/$regex/)

根据您希望在什么位置应用模板替换来移动它们。

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

regex = ^\d+(??{$stored_regex})$
但您需要通过在Perl程序中执行以下操作,在使用regexp的块中禁用安全检查:

use re 'eval';

一个切向相关的问题:如果您内联执行双插值,并且变量中也有替换字符串,请考虑:

# the concat with doublequotes in the replacement string 
#  are to make them PART OF THE STRING, NOT THE STRING DELIMITERS,
#  in other words, so the 2nd interpolation sees a double quoted string :
#     eval eval $replace -> eval $1 hello world -> syntax error 
#     eval eval $replace -> eval "$1 hellow world"  -> works ok 
# see: http://www.perlmonks.org?node_id=687031  

if($line =~ s/$search/'"' . $replace . '"'/ee) {
     # STUFF... 
}