Search and replace pattern

I want to search and replace a pattern but only if it occurs between two other patterns. How can this be achieved?

I have multiple occurances of the pattern which I want to replace in the string but I want to replace only one instance which occurs between two other patters.
"This is a good question and asks for a good answer"

I want to replace the good which only if it occurs somewhere between "for" and "answer" with bad
Who is Participating?
#!/usr/bin/perl -w
use strict;

my $str = "This is a good question and asks for a good answer";
$str =~ s/(?<=for a) good (?=answer)/ bad /g;
print $str;
$str =~ s/(\bfor.*)\bgood\b(.*\banswer\b)/$1bad$2/s;
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.