Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/11.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_Capture - Fatal编程技术网

Regex Perl:使用变量传递正则表达式搜索和替换

Regex Perl:使用变量传递正则表达式搜索和替换,regex,perl,capture,Regex,Perl,Capture,我有一个Perl脚本,它读取正则表达式搜索并替换INI文件中的值 在我尝试使用捕获变量($1或\1)之前,这一切都很正常。这些将被替换为$1或\1 有没有办法让这个捕获功能通过变量传递正则表达式位?示例代码(不使用ini文件) 这导致 word1 word2 GENERIC $4 不是 谢谢使用双重评估: $search = q((\S+)\s+(summary message)); $replace = '"GENERIC $1"'; $test =~ s/$search/$replace

我有一个Perl脚本,它读取正则表达式搜索并替换INI文件中的值

在我尝试使用捕获变量($1或\1)之前,这一切都很正常。这些将被替换为$1或\1

有没有办法让这个捕获功能通过变量传递正则表达式位?示例代码(不使用ini文件)

这导致

word1 word2 GENERIC $4
不是


谢谢

使用双重评估:

$search = q((\S+)\s+(summary message));
$replace = '"GENERIC $1"';

$test =~ s/$search/$replace/ee;

注意
$replace
ee
s//

结尾处的双引号请尝试对regex sub进行eval,注意替换来自外部文件

eval "$test =~ s/$search/$replace/";

另一个有趣的解决方案是使用look aheads
(?=PATTERN)

您的示例将只替换需要替换的内容:

$test = "word1 word2 servername summary message";

# repl. only ↓THIS↓
$search = qr/\S+\s+(?=summary message)/;
$replace = q(GENERIC );

$test =~ s/$search/$replace/;
print $test;

如果您喜欢amon的解决方案,我假设“通用$1”不是配置(尤其是其中的“$1”部分)。在这种情况下,我认为有一种不使用look aheads的更简单的解决方案:

$test = "word1 word2 servername summary message";
$search = qr/\S+\s+(summary message)/;
$replace = 'GENERIC';
$test =~ s/$search/$replace $1/;

当然,虽然(?=模式)没有什么不好的地方。

您的搜索模式不会成功,但有!:在搜索模式的末尾,但不在字符串中。很抱歉,我犯了错误,!:应该从示例中删除
$test = "word1 word2 servername summary message";

# repl. only ↓THIS↓
$search = qr/\S+\s+(?=summary message)/;
$replace = q(GENERIC );

$test =~ s/$search/$replace/;
print $test;
$test = "word1 word2 servername summary message";
$search = qr/\S+\s+(summary message)/;
$replace = 'GENERIC';
$test =~ s/$search/$replace $1/;