Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

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
Replies are listed 'Best First'.
Re: Remove text within parenthesis
by choroba (Canon) 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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (14)
As of 2015-08-28 19:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The oldest computer book still on my shelves (or on my digital media) is ...













    Results (339 votes), past polls