--- Rene Verharen <[EMAIL PROTECTED]> wrote:
> Hi,
> 
> In one of my scripts I do a search and replace like this
> :
> 
>     $text =~ s/$search/$replace/;
> 
> This works fine, but if $search or $replace contains
> one or more words between round brackets () it doesn't
> what I had in mind :
> 
>     $text = "This is a text (with brackets)...";
>     $rearch = "(with brackets)";
>     $replace = "without brackets";
>     $text =~ s/$search/$replace/;
>     print $text;
> 
> If I run this example it prints :  This is a text
> (without brackets)...
> 
> Where did I go wrong ?

Mistyping $search?  :P  But that isn't the whole story...

$search and $replace are interpolated into the regex, not
as just a string but PART OF THE REGEX.  This means you
really have:

$text =~ s/(with brackets)/without brackets/;

when you really wanted:

$text =~ s/\(with brackets\)/without brackets/;

You can obviously put those escapes in, or alternatively
use:

$search = quotemeta "(with brackets)";

which does that bit of work for you.  Removing bracket
pairs (not nested), can be done using:

$text =~ s/\(([^)])*\)/$1/g;

which means:

$text =~ s/\(          # Match an opening bracket
           ([^)])*     # Capture non closing bracket
                       # characters and store into $1
           \)          # Match a closing bracket
          /
           $1          # Replace all we've matched
                       # with $1
          /g;          # Option:  Global replace

Take care,

Jonathan Paton

__________________________________________________
Do You Yahoo!?
Everything you'll ever need on one web page
from News and Sport to Email and Music Charts
http://uk.my.yahoo.com

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to