mie fmt
mie fmt

Reputation: 13

How can I add a string before every match?

How can I add word info as leading everywhere there is word matching zzzz with regex?

like infozzzz

#!/usr/bin/perl 

$string = " zzzz  mike  zzzz stone zzzz";
$string =~ m/zzzz/;

Upvotes: 1

Views: 485

Answers (1)

Timur Shtatland
Timur Shtatland

Reputation: 12347

Use the substitution operator like so:

$string =~ s/(zzzz)/info${1}/g;

Or simply:

$string =~ s/zzzz/info$&/g;

$variable =~ s/PATTERN/REPLACEMENT/g; : Replace PATTERN with REPLACEMENT in $variable.
(zzzz) : Match literal string zzzz, capture using parenthesis into capture variable $1.
$& : Capture variable that contains the entire matched PATTERN.
/g : A regex modifier that tells to match the pattern repeatedly.

SEE ALSO:
perldoc perlre: Perl regular expressions (regexes)
perldoc perlre: Perl regular expressions (regexes): Quantifiers; Character Classes and other Special Escapes; Assertions; Capture groups
perldoc perlrequick: Perl regular expressions quick start

Upvotes: 1

Related Questions