Search and replace pattern

Posted on 2006-05-17
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

    #!/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 84

    Assisted Solution

    $str =~ s/(\bfor.*)\bgood\b(.*\banswer\b)/$1bad$2/s;

    Featured Post

    Looking for New Ways to Advertise?

    Engage with tech pros in our community with native advertising, as a Vendor Expert, and more.

    Join & Write a Comment

    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…
    A year or so back I was asked to have a play with MongoDB; within half an hour I had downloaded (,  installed and started the daemon, and had a console window open. After an hour or two of playing at the command …
    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…
    It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.

    746 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

    Need Help in Real-Time?

    Connect with top rated Experts

    16 Experts available now in Live!

    Get 1:1 Help Now