re question - finiding matching ()

Peter Otten __peter__ at web.de
Sun Jan 18 17:58:47 EST 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
calls.

<example.py>
import compiler

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

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())
</example.py>

Peter



More information about the Python-list mailing list