Perl: finding and replacing a regex using variables

I have a Perl script that reads a regular expression search and replaces values ​​from an INI file.

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

Any ideas how I can get this capture function to work with the transmit bits of a regular expression through variables? Sample code (without using ini file) ...

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

It leads to...

 word1 word2 GENERIC $4 

NOT

 word1 word2 GENERIC summary message 

thanks

+6
source share
5 answers

Use double rating:

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

Note the double quotes in $replace and ee at the end of s/// .

+6
source

try regex-sub eval, warn that replacement comes from an external file

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

Another interesting solution would be to use options (?=PATTERN)

Your example will 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; 
0
source

If you like the amon solution, I assume that "GENERIC $ 1" is not a configuration (especially the "$ 1" part in it). In this case, I think there is an even simpler solution without using options:

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

Of course there is nothing wrong (? = PATTERN).

0
source

Use \ 4, not $ 4.

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

\ 4 is of particular importance to the RE engine.

-1
source

Source: https://habr.com/ru/post/920405/


All Articles