Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: How do I replace certain character if condition exists

by kilinrax (Deacon)
on Apr 17, 2003 at 13:14 UTC ( [id://251185]=note: print w/replies, xml ) Need Help??


in reply to How do I replace certain character if condition exists

Possibly a simplistic solution, but have you tried using negative lookahead? For instance:
abowley@krait:~$ (echo 'Madrid(Spain' && echo 'Madrid(Spain)') | perl +-pe 's/\((?![^)]*\))/ /g;' Madrid Spain Madrid(Spain)
Breaking the regex down:
s/ \( # an open bracket (?! # _not_ followed by [^)]* # anything except brackets (e.g. 'Spain') \) # followed by a bracket ) / /gz;

Replies are listed 'Best First'.
Re: Re: How do I replace certain character if condition exists
by Bilbo (Pilgrim) on Apr 17, 2003 at 13:41 UTC

    This works if you are sure that you won't have any nested parentheses. If you do then it doesn't work at all, for example:

    a(b(c))           becomes a b(c))
    a (b (c) d (e) f) becomes a  b (c) d (e) f)
    
      Well, you can do that with a regex, but it's a good degree more complicated.....
      abowley@krait:~$ (echo 'Madrid(Spain(Europe)' && echo 'Madrid(Spain(Eu +rope))' && echo 'Madrid(Spain Europe))' && echo 'a(b(c))' && echo 'a +(b (c) d (e) f)') | perl -mstrict -wpe 'BEGIN { $brackets = qr#\([^() +]*(?:(??{$brackets})[^()]*)*\)# }; s#([^)]+?)($brackets)([^(]+)# ( my + $s = $1 ) =~ tr/(/ /; ( my $e = $3 ) =~ tr/)/ /; $s . $2 . $e #ge;' Madrid Spain(Europe) Madrid(Spain(Europe)) Madrid(Spain Europe) a(b(c)) a (b (c) d (e) f)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (7)
As of 2024-04-23 12:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found