The excellent Simon Cozens tutorial at
http://www.perl.com/pub/2003/06/06/regexps.html
shows how to use regex's to isolate parenthesised text within a string with handling of nested/multiple parentheses. Cozens constructs a recursive Regex, and uses the ( ??{ $regex_variable } ) construct to defer interpolation of the variable until execution. It works for me!:
$ cat p2.pl
#!/opt/perl5.16/bin/perl
use strict;
use warnings;
our $paren = qr/ # Need declared variable with use stri
+ct.
\(
(
[^()]+ # Not parens
|
(??{ our $paren }) # Another balanced group (not interpol
+ated yet)
)*
\)
/x; # 'x' means ignore whitespace, comment
+s.
my $stuff = "On the outside now then (we go( in( and in(&stop)(awhile)
+ ( further ))) but still (here) ) and now (for a while) we are out ag
+ain.";
$stuff =~ /($paren)/;
print "----------\n";
print "$stuff\n";
print "----------\n";
print $1 . "\n";
print "----------\n";
$ ./p2.pl
----------
On the outside now then (we go( in( and in (&stop)(awhile) ( further )
+)) but still (here) ) and now (for a while) we are out again.
----------
(we go( in( and in (&stop)(awhile) ( further ))) but still (here) )
----------
$
But if I try to use the regex again it does not work as I think it ought. In the above code when I replace the matching regex with /($paren)^()*($paren)/ I expect $2 to be "(for a while)", but that does not work:
$ cat p3.pl
#!/opt/perl5.16/bin/perl
use strict;
use warnings;
our $paren = qr/ # Need declared variable with use stri
+ct.
\(
(
[^()]+ # Not parens
|
(??{ our $paren }) # Another balanced group (not interpol
+ated yet)
)*
\)
/x; # 'x' means ignore whitespace, comment
+s.
my $stuff = "On the outside now then (we go( in( and in (&stop)(awhile
+) ( further ))) but still (here) ) and now (for a while) we are out a
+gain.";
$stuff =~ /($paren)[^()]*($paren)/;
print "----------\n";
print "$stuff\n";
print "----------\n";
print $1 . "\n";
print "----------\n";
print $2 . "\n";
print "----------\n";
$ ./p3.pl
----------
On the outside now then (we go( in( and in (&stop)(awhile) ( further )
+)) but still (here) ) and now (for a while) we are out again.
----------
(we go( in( and in (&stop)(awhile) ( further ))) but still (here) )
----------
----------
$
$2 is empty. Does anyone know what is going on here? If I take out the ^()+ portion of the regex, then the program hangs when I run it.