Fellow Monks, I've recently tackled a code update project at my day job that involves scanning program code for some crummy stuff and replacing it with smart stuff. (The code is Business Basic, for those interested). At any rate, the bad code attempts to PRINT some ASCII terminal control characters that are better represented by a sequence that is not terminal-type dependent. An example line looks like:
10 PRINT "<29>This should be dim.<30>EThis should be reversed.<28>This + is bold."
And so on. The pieces that look like <\d+> are what I'm interested in. What this should be replaced with is:
10 PRINT @(-38);"This should be dim.";@(-37);"This should be reversed. +";@(-40);"This is bold."
OK, no problem. So I set up a hash with keys in it like '<29>' and a value like '@(-38);'. And, using the /g switch of the pattern match operator, I can do:
while ($line=~/(<\d+>)/g) { next if ($1 eq '<30>'); $line=~s/$1/$fix{$1}/; }
I've ignored the codes like <30>E because they are a slighty different pattern, and I want to keep the code simple so I can set up a similar loop for those.
The problem is those darn double quotes in the PRINT statement. As you can see from the desired output, regular text should be bracketed in quotes but those ASCII codes should be changed to the @ statments outside quotes!
So can anyone come up with either a pattern match or substitute operator to successfuly change the bad line to the good? I believe this could be done with pos() and index() but that would be a lot of repetition in the code, and slick RegEx's are so much nicer :)

Thanks for any ideas


In reply to Smart Search and Replacement with RegEx by shelob101

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.