Ok ok.. loosen your belts.. rolls your eyes, crack your knuckles or maybe close your eyes and randomly punch the keyboard - here's a regex question!

I have a string as such: 423RY75Y69827EC67592C78657N965R

It has to be turned into 423R_Y75Y_69827E_C67592C_78657N965R

What's the idea? The idea is, first and foremost.. if any digits are sandwiched between two letters, then put an underscore to the sides of this group... However, treat N characters as we would digits.

#!/usr/bin/perl -w use strict; use Smart::Comments; my $string = '423RY75Y69827EC67592C78657N965R345U299M'; my $correct = '423R_Y75Y_69827E_C67592C_78657N965R_345U_299M'; $string=~s/([A-MO-Za-mo-z])([\dN]+)\1/_$1$2$1_/g; ### $string # is now '423R_Y75Y_69827E_C67592C_78657N965R345U299M' # now i have troubles.. # the idea is to match right to left, and if after (the last digit # or N char), place an underscore, unless of course, that char is the # char we started with! $string=~s/([^\dN\3])([\dN]+)([A-MO-Za-mo-z])/$1_$2$3/g; ### $string # is now '423R_Y_75Y__69827E_C_67592C__78657N965R345U_299M' # wow, seems to have done the reverse of what i wanted!

I'm having real trickies here . . it's like reverse memory or something that the regex has to do.. ow..


In reply to match if last char and first char are different excluding certain chars by leocharre

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.