The easy fix is to just simply capture the closing bracket as well:

$ab=~s/ \{ \s* eval ([^\}]+ \}) \s* \} /$1/egx; # x modifier added for clarity

However, your code does have other problems. For instance, the inner blocks (the ones in which the eval is located) may contain other statements besides the eval. The eval-block may itself contain inner blocks as well as containing strings that contain brackets. As it stands, all of these cases will cause your regex to fail. Although you may be able to ignore many of them if you are working within a closed system (i.e., you are in control of the input), it seems that you at least need to worry about strings containing brackets. If you do in fact need to worry about parsing full code, then you may want to consider using a full parsing system like Parse::Recdescent.

For help in dealing with parsing arbitrary code, you can take a look at Parsing with Perl 6. Although the article deals with parsing code using Perl6 regular expressions, it also provides Perl5 equivalant code at the bottom which you can probably make use of.


In reply to Re: Cleaner Regex by jryan
in thread Cleaner Regex by InfiniteSilence

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.