'Perl string replace: Match, but not replace, part of regex
Say I have a string in Perl I am trying to match and replace with stuff:
$string =~ s/[^a-zA-Z]$find[^a-zA-Z]/$replace/g;
So as shown, I want to replace everything that is surrounded on both sides by nonletter characters. However, when I replace the string, I do NOT want to also replace these characters: they are just necessary for correct matching. How can I tell the Perl regex to avoid replacing the things surrounding $find?
Solution 1:[1]
Store them as a matched group, and reference them in the replacement string:
$string =~ s/([^a-z])$find([^A-Z])/\1$replace\2/gi;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | hjpotter92 |
