re question - finiding matching ()

Peter Otten __peter__ at
Sun Jan 18 23:58:47 CET 2004

Miki Tebeka wrote:

> To all of you regexp gurus out there...

So not asking me, but anyway...

> I'd like to find all of the sub strings in the form "add(.*)"
> The catch is that I might have () in the string (e.g. "add((2 * 2),
> 100)"),
> Currently I can only get the "addr((2 *2)" using
> re.compile("\w+\([^\)]*\)"). To solve the problem a hand crafted search is
> used :-(
> Is there a better way?

Iff you are looking into Python code, you could also use the compiler
module. The following script scans itself for occurences of add() function

import compiler

def sample():
    """ add(xxx) <- will not be found """
    x.add(1) # <- will not be found
    add(a, b)

class Visitor:
    def visitCallFunc(self, node):
        if getattr(node.getChildren()[0], "name", None) == "add":
            print node

tree = compiler.parseFile(__file__)

compiler.visitor.walk(tree, Visitor())


More information about the Python-list mailing list