Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium


Search and replace pattern

Posted on 2006-05-17
Medium Priority
Last Modified: 2010-05-18
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
Question by:rohit_kapil
LVL 17

Accepted Solution

mjcoyne earned 100 total points
ID: 16701602
#!/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;
LVL 85

Assisted Solution

ozo earned 100 total points
ID: 16701736
$str =~ s/(\bfor.*)\bgood\b(.*\banswer\b)/$1bad$2/s;

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I've just discovered very important differences between Windows an Unix formats in Perl,at least 5.xx.. MOST IMPORTANT: Use Unix file format while saving Your script. otherwise it will have ^M s or smth likely weird in the EOL, Then DO NOT use m…
On Microsoft Windows, if  when you click or type the name of a .pl file, you get an error "is not recognized as an internal or external command, operable program or batch file", then this means you do not have the .pl file extension associated with …
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Six Sigma Control Plans
Suggested Courses

571 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question