... this seems to work?

Actually, no! Let's try it.

knoppix@Microknoppix:~$ perl -E ' > $_ = q{bbaaccbab sdcbalsbadcbnw}; > s/(\s\w+)ba/\1Ba/g; > say;' bbaaccbab sdcbalsBadcbnw knoppix@Microknoppix:~$

Notice how it has changed the second 'ba' to the right of the space rather than the first; that's because your \w+ is greedy so it matches as many characters as it can. Correcting that and running again.

knoppix@Microknoppix:~$ perl -E ' > $_ = q{bbaaccbab sdcbalsbadcbnw}; > s/(\s\w+?)ba/\1Ba/g; > say;' bbaaccbab sdcBalsbadcbnw knoppix@Microknoppix:~$

Now we have changed the first 'ba' but, hang on, the second 'ba' has not been changed. That's because after the first replacement the regex engine has consumed the string up to and including the first 'ba' and is positioned in front of the next character, the 'l'. When the next match is attempted you are looking for a space followed by word characters but there is no space there so the match fails. If we try to correct that by making the space optional then the match does work more than once but the 'ba' sequences to the left of the space also get changed.

knoppix@Microknoppix:~$ perl -E ' > $_ = q{bbaaccbab sdcbalsbadcbnw}; > s/(\s?\w+?)ba/\1Ba/g; > say;' bBaaccBab sdcBalsBadcbnw knoppix@Microknoppix:~$

It seems, perhaps, that this problem is a bit tricky to solve without using look-around assertions.

Cheers,

JohnGG


In reply to Re^2: Work-around for variable length look-behind? by johngg
in thread Work-around for variable length look-behind? by pat_mc

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.