Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

Remove text within parenthesis

by firmament (Novice)
on May 07, 2013 at 21:49 UTC ( #1032535=perlquestion: print w/ replies, xml ) Need Help??
firmament has asked for the wisdom of the Perl Monks concerning the following question:

I'm looking to remove some text within parantheses, thinking like this:
my $s = "bla bla (parenthesis) somestring"; if ($s =~ /.*(\(parenthesis\))\s*somestring/) { print "matched $1\n"; #this prints "(parenthesis)" $s =~ s/$1//; # $s now looks "bla bla () somestring" rather than the desired + "bla bla somestring" }
But even though $1 when printed includes the parenthesis, the substitution statement does not remove them. Am I missing something trivial (probably)? Many thanks.

Comment on Remove text within parenthesis
Download Code
Re: Remove text within parenthesis
by choroba (Abbot) on May 07, 2013 at 22:11 UTC
    To avoid the interpretation of parentheses inside $1, use \Q:
    $s =~ s/\Q$1//;

    Note that this is still not the desired "bla bla somestring" because there are two spaces after the bla bla.

    لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
      Thanks a lot for the \Q advice, very interesting.
Re: Remove text within parenthesis
by Anonymous Monk on May 07, 2013 at 22:14 UTC
    Try  $s =~ s{ \(parenthesis\) }{}x;
Re: Remove text within parenthesis
by gurpreetsingh13 (Scribe) on May 08, 2013 at 03:52 UTC
    Or just a simple regex should work. What about this?
    $s =~ s/(.*)\s(\(.*\))\s(.*)/$1 $3/g; print "matched $2\n"; print $s;
Re: Remove text within parenthesis
by jnyman (Acolyte) on May 08, 2013 at 12:06 UTC
    If you have nested parentheses, the solution is somewhat more complex:
    use 5.014; my $s = "a (d (b) (e (f) ) ) c"; say remove_par($s); sub remove_par { my ( $result, $open ); foreach my $ch ( split // => shift ) { $open++ if $ch eq '('; $open-- if $ch eq ')'; $result .= $ch if !$open && $ch ne ')'; } die "non-matching parentheses" if $open; return $result; };

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1032535]
Front-paged by Corion
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (6)
As of 2014-12-21 02:40 GMT
Find Nodes?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?

    Results (101 votes), past polls