简体   繁体   中英

Perl: passing regex search and replace using variables

I have a Perl script that reads regex search and replace values from an INI file.

This works fine until I try to use capture variables ($1 or \\1). These get replaced literally with $1 or \\1.

Any ideas how I can get this capture functionality to work passing regex bits via variables? Example code (not using an ini file)...

$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/// .

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

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

Another interesting solution would use look-aheads (?=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). 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.

Use \\4, not $4.

$4 has no special meaning in q(), nor does RE engine recognize it.

\\4 has special meaning to RE engine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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