Regex 如何获取JSON值中的动态变量?

Regex 如何获取JSON值中的动态变量?,regex,perl,Regex,Perl,我需要通过正则表达式使用find和replace,如下所示 use strict; no strict 'refs'; use warnings; use JSON; use Encode qw( encode decode encode_utf8 decode_utf8); my $data = { "find_replace" => [ { "find" => "(.+?)&", "replace"=> "$

我需要通过正则表达式使用find和replace,如下所示

use strict;
no strict 'refs';
use warnings;
use JSON;
use Encode qw( encode decode encode_utf8 decode_utf8);

my $data =  
{
    "find_replace" => [
        {   "find" => "(.+?)&",
            "replace"=> "$1"
        }
    ]
};

my $find_replace_arr = $data->{'find_replace'};
my $string  = "http://www.website.com/test.html&code=236523";

my $find = $find_replace_arr->[0]->{find};
my $replace = $find_replace_arr->[0]->{replace};

$string =~ s/$find/$replace/isge;

print $string;
exit();
在这段代码中,我只想从字符串中删除“”

我无法动态获取replace(key)的值,即$1

您可以运行上面的代码

此代码在字符串中使用未初始化值$1时抛出错误


有些事情要考虑。首先,正则表达式
([^&]+)
可能不会给出所需的结果,因为它实际上将捕获并替换为相同的捕获。。产生相同的输出字符串(我打赌这会让人困惑)

接下来,必须再次引用替换字符串
“$1”
,并且
e
修饰符必须加倍

所以试试这个:

my $data =  
{
    "find_replace" => [
        {   "find" => "^(.+?)&.*",
            "replace"=> '"$1"'
        }
    ]
};

my $find_replace_arr = $data->{'find_replace'};
my $string  = "http://www.website.com/test.html&code=236523";

my $find = $find_replace_arr->[0]->{find};
my $replace = $find_replace_arr->[0]->{replace};

$string =~ s/$find/$replace/isgee;

print $string;
exit();

<新的正则表达式>代码> ^(.+)和*>代码>将匹配整个字符串,但是捕获<代码>(…)>代码>将是替换的结果。

一些要考虑的事情。首先,正则表达式
([^&]+)
可能不会给出所需的结果,因为它实际上将捕获并替换为相同的捕获。。产生相同的输出字符串(我打赌这会让人困惑)

接下来,必须再次引用替换字符串
“$1”
,并且
e
修饰符必须加倍

所以试试这个:

my $data =  
{
    "find_replace" => [
        {   "find" => "^(.+?)&.*",
            "replace"=> '"$1"'
        }
    ]
};

my $find_replace_arr = $data->{'find_replace'};
my $string  = "http://www.website.com/test.html&code=236523";

my $find = $find_replace_arr->[0]->{find};
my $replace = $find_replace_arr->[0]->{replace};

$string =~ s/$find/$replace/isgee;

print $string;
exit();

请注意新的正则表达式,
^(+?)&.*
将匹配整个字符串,但捕获的
(…)
将是要替换的结果。

由于替换变量包含Perl代码,请尝试向正则表达式添加
e
修饰符:
my$string=~s/$find/$replace/isge
您好,谢谢您的回答,我检查了你的代码并修改了上面的代码。但仍然不起作用。在stringYes中使用未初始化值$1会出现错误。您是对的。在这种情况下,您需要将
e
修饰符加倍,因为您的replace变量包含Perl代码,请尝试将
e
修饰符添加到正则表达式中:
my$string=~s/$find/$replace/isge
您好,哈肯谢谢您的回答,我检查了您的代码并修改了上面的代码。但仍然不起作用。在stringYes中使用未初始化值$1会出现错误。您是对的。在这种情况下,您需要将
e
修饰符加倍