CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Remove text within brackets and return the remaining string

 



PerlBeginner31
Novice

Apr 30, 2014, 4:01 AM

Post #1 of 4 (3360 views)
Remove text within brackets and return the remaining string Can't Post

For the following sample input string,
a.b(c).d(e(f.g)).h

The output should be
a.b.d.h

I want the text within the brackets to be removed.

Can someone help me with the code?


Laurent_R
Veteran / Moderator

Apr 30, 2014, 4:25 AM

Post #2 of 4 (3357 views)
Re: [PerlBeginner31] Remove text within brackets and return the remaining string [In reply to] Can't Post

If you allow nested parentheses as in your example, this is getting possibly beyond what single regexes can do, especially if there may be 3, 4 or more paren nesting levels. You should probably settle for a primitive parser that can maintain a counter of how many opening unclosed parens it has seen.

Without nested parens, the regex could be something like this:

Code
s/\(.+?\)//g;



BillKSmith
Veteran

Apr 30, 2014, 5:41 AM

Post #3 of 4 (3354 views)
Re: [Laurent_R] Remove text within brackets and return the remaining string [In reply to] Can't Post

Use the module Regexp::Common qw(balanced) to build the regular expression for you.

Code
use strict; 
use warnings;
use Regexp::Common qw(balanced);
my $string = 'a.b(c).d(e(f.g)).h';
$string =~ s/$RE{balanced}{-parens=>'()'}//g;
print $string, "\n";


OUTPUT:

Code
a.b.d.h


Update: Added example.
Good Luck,
Bill

(This post was edited by BillKSmith on Apr 30, 2014, 5:55 AM)


Laurent_R
Veteran / Moderator

Apr 30, 2014, 10:18 AM

Post #4 of 4 (3271 views)
Re: [BillKSmith] Remove text within brackets and return the remaining string [In reply to] Can't Post

Hi Bill,

I did not think about Regexp::Common qw(balanced), this is an excellent solution.

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives