Monks,

I'm trying to solve a difficult (for me at least) regex substitution problem. I think part of the issue is I am trying to use a regex where a short parser implementation would be more appropriate, but I'm Lazy, and hoping that I can coerce Perl's regex engine into doing the work for me. Onto the problem at hand (please ignore whitespace inconsistencies in the content).

my $content = <<CONTENT; foo somestuff zimzam someotherstuff bar evenmorestuff foo bar zimzam foo zimzam bar CONTENT my $orig_zimzam = 'zimzam'; my $rep_zimzam = 'zoomzam'; $content =~ s/(foo(?!bar).*?)\Q$orig_zimzam\E(.*?bar)/$1$rep_zimzam$2/ +sg; print $content;

The regex I have in this post is one of many variations that I've tried, but this content test case seems to foil all of them. I've used use re 'debug' to look at the inner goodness of what's going on with the regex, but I am coming up empty.

In short, I'm trying to replace all instances of zimam nested between foo and bar, with zoomzam. Strange names, but I've boiled the bigger problem down to a test case here that fails. Here's the current output.

foo somestuff zoomzam someotherstuff bar evenmorestuff foo bar zoomzam foo zimzam bar

And the expected output

foo somestuff zoomzam someotherstuff bar evenmorestuff foo bar zimzam foo zoomzam bar

Any ideas? (some whitespace formatting is incorrect, please ignore it)


In reply to Substitution with matching nested boundary conditions by redhotpenguin

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.