Sure, here's a start:

$n =~ s/(^| )$a( |$)/$1$b$2/i;

You can avoid the $1..$2 in the substitution if you can avoid capturing the spaces, which you can do by matching with lookahead/lookbehind:

$n =~ s/(^|(?<= ))$a((?= )|$))/$b/i;

Or inverse the sense of the lookarounds: "not after a non-space" rather than "after a space, or after nothing":

$n =~ s/(?<![^ ])$a(?![%a])/$b/i;

Note that the first version is adequate for most purposes, but may trip you up if you want to do a global substitution for all copies of $a:

"FOO foo" =~ s/(^| )foo( |$)/${1}bar$2/ig
.. will catch the 'FOO' but not the 'foo', because having used the space as part of the first match the regexp engine will start trying to perform a second match starting at the 'f'.

The other two version do not suffer from that problem, since the lookarounds don't affect where a future match will start.

Hugo


In reply to Re: regexp help -- word boundaries by hv
in thread regexp help -- word boundaries by water

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.