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?
In reply to Eternal question of parsing parentheses by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |