Replace specific capture group instead of entire regex in Perl

flohei picture flohei · Aug 26, 2012 · Viewed 14.9k times · Source

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.

Answer

Birei picture Birei · Aug 26, 2012

As I understand, you can use look-ahead or look-behind that don't consume characters. Or save data in groups and only remove what you are looking for. Examples:

With look-ahead:

s/your_text(?=ahead_text)//;

Grouping data:

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