in reply to Re: regex: Need help substituting
in thread regex: Need help substituting

I have understood that using regex for this problem is not the preferred method, at all. It was however my intention to learn more about regexp, so for now, with your help I have come up with (using the backwards strategy)

# First match ! $data =~ s|^(.*<section1>.*<rstate>).+(</rstate>.*</section1>.*)$| +$1$newrstate$2|s; # Second match! $data =~ s|^(.*<section2>.*<rstate>).+(</rstate>.*</subsection>.*< +/subsection>.*</subsection>.*</section2>.*)$|$1$newrstate$2|s; # Third match! $data =~ s|^(.*<section3>.*<rstate>).+(</rstate>.*</section3>.*)$| +$1$newrstate$2|s;

Curious as I am, I will read up on the XML parser and try it as well to see how it compares. Thanks for the help!

Replies are listed 'Best First'.
Re^3: regex: Need help substituting
by Joe_ (Beadle) on Apr 08, 2012 at 13:57 UTC

    I'm just curious as to why you're using the many if statements.
    I suppose the following should work:

    $data=~ s{<rstate>[^<\n]+</rstate>}{<rstate>$new_text</rstate>}g
    Note the use of the 'g' modifier.
    If you want to learn more about regular expressions in general, then Friedl's book is a must. It's one the most well-written books I've ever read on any subject and I highly recommend it.

      Hi, I don't anylonger. I approached the problem the wrong way, and all I have now is the three lines above to substitute <rstate> at different specific places in the file. Totally agree on the book! I ordered it a while ago but haven't had the time to read it. I'm going to now since I will have good use for regexp in my present work. Thanks

        Enjoy it. It's such a great read! It improved my regexes by orders of magnitude...