As always, the more examples, the better - see How to ask better questions using Test::More and sample data. For example, can there be other parentheses anywhere in the string? Can there be text after the parentheses that you want to capture? etc.
Here's one way that works even when there are multiple sets of parentheses and strings outside of them.
use warnings; use strict; my $str1 = "THIS IS OUTSIDE (THIS IS INSIDE)"; (my $x = $str1) =~ s/\(.*?\)//g; # $x is "THIS IS OUTSIDE " my $str2 = "OUTSIDE (INSIDE) OUTSIDE"; (my $y = $str2) =~ s/\(.*?\)//g; # $y is "OUTSIDE OUTSIDE" my $str3 = "OUT(IN)OUT(IN)OUT(IN)(IN)OUT"; (my $z = $str3) =~ s/\(.*?\)//g; # $z is "OUTOUTOUTOUT"
The above does not work for nested parens, though. For that, you could use Regexp::Common::balanced:
use Regexp::Common qw/balanced/; my $str4 = "a(b(c(d)e)f)g(h(i(j)k)l)m"; (my $t = $str4) =~ s/$RE{balanced}{-parens=>'()'}//g; # $t is "agm"
In reply to Re: Regex for outside of brackets
by haukex
in thread Regex for outside of brackets
by theravadamonk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |