简体   繁体   English

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

[英]Perl: passing regex search and replace using variables

I have a Perl script that reads regex search and replace values from an INI file. 我有一个Perl脚本,它读取正则表达式搜索并替换INI文件中的值。

This works fine until I try to use capture variables ($1 or \\1). 这工作正常,直到我尝试使用捕获变量($ 1或\\ 1)。 These get replaced literally with $1 or \\1. 这些用$ 1或\\ 1替换。

Any ideas how I can get this capture functionality to work passing regex bits via variables? 任何想法如何让这个捕获功能通过变量传递正则表达式位? Example code (not using an ini file)... 示例代码(不使用ini文件)...

$test = "word1 word2 servername summary message";

$search = q((\S+)\s+(summary message));
$replace = q(GENERIC $4);

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

This results in ... 这导致......

word1 word2 GENERIC $4

NOT

word1 word2 GENERIC summary message

thanks 谢谢

Use double evaluation: 使用双重评估:

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

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

Note double quotes in $replace and ee at the end of s/// . 注意$replace s///双引号和@ s///末尾的ee

尝试将regex-sub置于eval,请注意替换来自外部文件

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

Another interesting solution would use look-aheads (?=PATTERN) 另一个有趣的解决方案是使用前瞻(?=PATTERN)

Your example would then only replace what needs to be replaced: 那么您的示例只会替换需要替换的内容:

$test = "word1 word2 servername summary message";

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

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

If you like amon's solution, I assume that the "GENERIC $1" is not configuration (especially the '$1' part in it). 如果你喜欢amon的解决方案,我认为“GENERIC $ 1”不是配置(尤其是'$ 1'部分)。 In that case, I think there's an even more simple solution without the use of look-aheads: 在这种情况下,我认为有一个更简单的解决方案,而不使用预测:

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

Although there's nothing really bad about (?=PATTERN) of course. 当然,(?= PATTERN)并没有什么不好的。

Use \\4, not $4. 使用\\ 4,而不是4美元。

$4 has no special meaning in q(), nor does RE engine recognize it. $ 4在q()中没有特殊含义,RE引擎也没有识别它。

\\4 has special meaning to RE engine. \\ 4对RE引擎有特殊意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM