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

Advanced replace function

by sans-clue (Beadle)
on Dec 04, 2009 at 19:02 UTC ( [id://811143]=perlquestion: print w/replies, xml ) Need Help??

sans-clue has asked for the wisdom of the Perl Monks concerning the following question:

If I have a string like this
$str="abc t[poop1] def [doop2] [woop3] xyz";

I wish to replace the brackets and what is inside with a string like ~~ so that the resultant string is
"abc t~~ def ~~ ~~ xyz"
how would I do that, considering there can be any number of [blah] in the string. Thanks

Replies are listed 'Best First'.
Re: Advanced replace function
by kyle (Abbot) on Dec 04, 2009 at 19:08 UTC

    You may be looking for the /g option to s///:

    my $str="abc t[poop1] def [doop2] [woop3] xyz"; $str =~ s/\[.*?\]/~~/g; print "$str\n"; __END__ abc t~~ def ~~ ~~ xyz
      There was nothing about newlines being disallowed in the brackets. The following is faster and more likely to match correctly:
      s/\[.*?\]/~~/sg

      But that's risky, especially if you use it a larger pattern. The /.*?/ could match a "[" or a "]". That's obviously undesirable. The following pattern avoids that problem:

      s/\[[^\[\]]*\]/~~/g;
Re: Advanced replace function
by ww (Archbishop) on Dec 04, 2009 at 20:03 UTC

    ... or, one of several possible alternates, on the off chance (ymmv) you find this will be easier to read someday, down the road:

    my $regex = qr'(?:\[.*?\])'; compile regex; use non-capture grouping $str =~ s/$regex/~~/g;

      You are advocating building small patterns so that they can be combined into larger patterns, right? If so, your code is buggy (and I don't mean just the superfluous (?:)).

      >perl -E"$sqr=qr/\[.*?\]/; $_='ab[cd]ef[gh]'; s/$sqr$//; say" ab

      Fixed:

      >perl -E"$sqr=qr/\[[^\[\]]*\]/; $_='ab[cd]ef[gh]'; s/$sqr$//; say" ab[cd]ef

       qr// automatically wraps its expression in a non-capturing group:

      >perl -wMstrict -le "my $regex = qr'(?:\[.*?\])'; print $regex; " (?-xism:(?:\[.*?\]))

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (3)
As of 2024-03-28 15:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found