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.
e.g
"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
rohit_kapilAsked:
Who is Participating?
 
mjcoyneCommented:
#!/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;
0
 
ozoCommented:
$str =~ s/(\bfor.*)\bgood\b(.*\banswer\b)/$1bad$2/s;
0
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.