Hello brothers,

I have a string that looks like "aabbxxcccdadenmmpyyx". I want to find every pair of identical characters (e.g. aa) and put an 'x' between them (i.e. axa).

With a few milliseconds worth of thought, I came up with the following:

$str =~ s/(.)\1/$1x$1/g;

This works for double characters -- HOWEWER, the string shown above, once processed, looks like:

"axabxbxxxcxccdadenmxmpyxyx"

Note the ccc in the original turned to cxcc, whereas I wanted cxcxc. The problem here is that the regexp "cursor" points to the third c when it had matched the cc pair. It process the cc pair to cxc, and continued on its merry old way starting with the third c.

Any clues how to solve this interesting problem using a regexp (and not resorting to popping characters off the string using substr or the like).

Cheers
Andy
--


In reply to Matching double characters and insertion by Anonymous Monk

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.