繁体   English   中英

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

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

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

这工作正常,直到我尝试使用捕获变量($ 1或\\ 1)。 这些用$ 1或\\ 1替换。

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

$test = "word1 word2 servername summary message";

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

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

这导致......

word1 word2 GENERIC $4

word1 word2 GENERIC summary message

谢谢

使用双重评估:

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

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

注意$replace s///双引号和@ s///末尾的ee

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

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

另一个有趣的解决方案是使用前瞻(?=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的解决方案,我认为“GENERIC $ 1”不是配置(尤其是'$ 1'部分)。 在这种情况下,我认为有一个更简单的解决方案,而不使用预测:

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

当然,(?= PATTERN)并没有什么不好的。

使用\\ 4,而不是4美元。

$ 4在q()中没有特殊含义,RE引擎也没有识别它。

\\ 4对RE引擎有特殊意义。

暂无
暂无

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

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