Replace specific capture group instead of all regular expression in Perl

I have a regex with capture groups that match what I want in a wider context. Then I take the capture group $1and use it for my needs. It's simple.

But how to use capture groups with s///when I just want to replace the contents $1, not the entire regular expression, with my replacement?

Thank!
-f

+5
source share
3 answers

If you only need to replace one capture, then using @LAST_MATCH_STARTand @LAST_MATCH_END(s use English; see perldoc perlvar) together with substrmay 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"
+1

, look-ahead look-behind, . , . :

:

s/your_text(?=ahead_text)//;

:

s/(your_text)(ahead_text)/$2/;
+12

This is an old question, but I found below it is easier to replace the lines starting with >somethingbefore >something_else. Good for changing headers for fasta sequence p>

  while ($filelines=~ />(.*)\s/g){
        unless ($1 =~ /else/i){
                $filelines =~ s/($1)/$1\_else/;
        }

  }
+1
source

All Articles