Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
In a string containing nested parentheses, I want to find the first parenthesis, in order to evaluate things for that before the rest. So for $_='a(b(c(d)(e))f)g(h)((i)j)'; the result should be b(c(d)(e))f.
This can be done the sad and boring way by splitting the string and going through it, counting parenthesis signs as you go. But surely there must be some clever regex to do it?
I came up with one solution, which looks wonderfully cryptic:
while(/^[^\(]*\([^\)]*\(/){s/\(([^\(\)]*)\)/\[\1\]/} s/.*?\((.*?)\).*/\1/; tr/\[\]/\(\)/;
Explanation:
While the first '(' is follwed by another '(' before any ')', i.e. the first parenthesis has inner parentheses, find the first '(' which is NOT followed by another '(' before the ')', i.e. the first innermost parenthesis, and replace that with [...]. Then extract the first remaining parenthesis, and replace all [ ] with ( ).
Is this a good idea? Can you improve it? Is there a better way?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Eternal question of parsing parentheses
by JavaFan (Canon) on Oct 24, 2009 at 13:23 UTC | |
|
Re: Eternal question of parsing parentheses
by ikegami (Patriarch) on Oct 24, 2009 at 16:39 UTC | |
|
Re: Eternal question of parsing parentheses
by LanX (Saint) on Oct 24, 2009 at 17:44 UTC | |
by LanX (Saint) on Oct 24, 2009 at 20:13 UTC | |
by AnomalousMonk (Archbishop) on Oct 24, 2009 at 18:46 UTC |