In general that is not really a job for a regex, it is a job for a parser. The issue is that generally it is messy to handle balanced text with regexen (not impossible with Perl regexes, but messy). If the commands were simple and it was not possible to have [, ], { or } in the 'commands etc' then the job is fairly trivial, but that is not the case.

Your simplest option may be to roll your own simple recursive decent parser for the job. Consider:

use strict; use warnings; while (defined (my $line = <DATA>)) { next unless $line =~ /^(catch\s*)\[(.*)/s; my $prefix = $1; my ($body, $tail) = parse ($2); $line = "${prefix}{$body}$tail"; } continue { print $line; } sub parse { my ($tail) = @_; my $outStr = ''; while (defined $tail) { if ($tail =~ s/^([^[]*)\[(.*)//s) { my $prefix = $1; my $body; ($body, $tail) = parse ($2); $outStr .= "$prefix [$body]"; next if length $tail; } elsif ($tail =~ s/^([^\]]*)](.*)//s) { return "$outStr$1", $2; } $outStr .= $tail; $tail = <DATA>; } return $outStr, ''; } __DATA__ catch [ this; that; the; other; ] some random stuff that isn't a catch catch [ this[]; that + 1; the other; ]

Prints:

catch { this; that; the; other; } some random stuff that isn't a catch catch { this []; that + 1; the other; }

although there are likely to be many special cases (quoted or commented unbalanced brackets for example) that mean that a heavier duty parser like Parse::RecDecent may be what you really need.


Perl reduces RSI - it saves typing

In reply to Re: Search and Replace on multi line ability by GrandFather
in thread Search and Replace on multi line ability by gio001

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.