matching balanced parens

I

ivo welch

I have tried for a while to figure out how to use the experimental
perl regex balanced paren feature (perlfaq6), but failed. if this is
possible, could someone please give me an example of the magic
invokation?

$text= "this is \macro{a { irrelevant } b} and this is \macro{c
{e{}}{} d}"
$text=~ s/\macro{ [matching .* to closing] }/\macro{***}/g; # help
here
and I would get
$text eq "this is \macro{***} and this is \macro{***}"

Is this even possible with regex? If not, could someone please point
me to the recommended method for global balanced substitutions (not
just matching)?

help appreciated. /iaw
 
G

Gunnar Hjalmarsson

ivo said:
I have tried for a while to figure out how to use the experimental
perl regex balanced paren feature (perlfaq6), but failed. if this
is possible, could someone please give me an example of the magic
invokation?

$text= "this is \macro{a { irrelevant } b} and this is \macro{c
{e{}}{} d}"
----^^
Don't know how to handle that third level of brackets, so I skipped it
in the example below.
$text=~ s/\macro{ [matching .* to closing] }/\macro{***}/g; # help
here
and I would get
$text eq "this is \macro{***} and this is \macro{***}"

The (??{ code }) example in perlre applied to two levels of brackets:

my $text = 'this is \macro{a { irrelevant } b}'
.' and this is \macro{c {e}{} d}';

my $re = qr(
{
(?:
(?> [^{}]+ )
|
(??{ $re })
)*
}
)x;

$text =~ s/(\\macro)$re/$1\{***}/g;
 
I

ivo welch

thanks, gunnar. you made more headway than I did. (Now at least I
know how to use the code from the perlfaq6! this would make a good
example to include.) Alas, my need is to be able to parse reasonable
latex source code, where these parens can be nested in many possible
ways. A genuine matching counter would definitely be nice to have as
a feature in regex like expressions. I still wonder if this is
possible.

if not, what is the recommended way? Splitting all characters into a
perl array seems wasteful. Working character by character with
substr($t, $c, 1) to do paren counting also somehow seems contrary to
the spirit of perl.


Regards,

/iaw
 
B

Ben Morrow

I have tried for a while to figure out how to use the experimental
perl regex balanced paren feature (perlfaq6), but failed. if this is
possible, could someone please give me an example of the magic
invokation?

Use Text::Balanced from CPAN.

Ben
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,775
Messages
2,569,601
Members
45,182
Latest member
alexanderrm

Latest Threads

Top