Replace specific capture group instead of entire regex in Perl
capture-group, perl, regex, replace
Solution
If you only need to replace one capture then using `@LAST_MATCH_START` and `@LAST_MATCH_END` (with `use English`; see `perldoc perlvar`) together with `substr` might be a viable choice:
use English qw(-no_match_vars);
$your_string =~ m/aaa (bbb) ccc/;
substr $your_string, $LAST_MATCH_START[1], $LAST_MATCH_END[1] - $LAST_MATCH_START[1], "new content";
# replaces "bbb" with "new content"
Problem
I've got a regular expression with capture groups that matches what I want in a broader context. I then take capture group `$1` and use it for my needs. That's easy. But how to use capture groups with `s///` when I just want to replace the content of `$1`, not the entire regex, with my replacement? For instance, if I do: ``` $str =~ s/prefix (something) suffix/42/ ``` `prefix` and `suffix` are removed. Instead, I would like `something` to be replaced by `42`, while keeping `prefix` and `suffix` intact.