Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number

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.

Replies are listed 'Best First'.
Re: Remove text within parenthesis
by choroba (Bishop) 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 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; };
Re: Remove text within parenthesis
by Anonymous Monk on May 07, 2013 at 22:14 UTC
    Try  $s =~ s{ \(parenthesis\) }{}x;

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1032535]
Front-paged by Corion
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (4)
As of 2018-02-21 06:06 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (275 votes). Check out past polls.