1

I'm trying to detect functions between call-chains.

For example, I can use

re.search("([\w_]+)\((|[\W\d\w\,]+)\)", line)

to find

print(len("AA"))

but it is reasonably not compatible with code like:

print(i + len("AA") + j + len("BBB"))

Help me.

3
  • 1
    Do you want to parse Python code? Commented Oct 7, 2013 at 8:13
  • 4
    first, it's not a good idea to parse nested function calls with regex, since the language is not regular. second, you can use the ast modul to analyse python code Commented Oct 7, 2013 at 8:14
  • Maybe a profiler would help here to see a caller graph, e.g.: pydoc -k profile. BTW: "Help me." sounds a bit rude, "Please help me." would be more polite, but both are not needed here at SX. Commented Oct 7, 2013 at 11:52

2 Answers 2

1

Your needs may be better served by the ast module:

import ast

a = ast.parse('print(i + len("AA") + j + len("BBB"))')
print ast.dump(a)

>>>
Module(body=[Print(dest=None, values=[BinOp(left=BinOp(left=BinOp(left=Name(id='i',
ctx=Load()), op=Add(), right=Call(func=Name(id='len', ctx=Load()), args=[Str(s='AA')], 
keywords=[], starargs=None, kwargs=None)), op=Add(), right=Name(id='j', ctx=Load())), 
op=Add(), right=Call(func=Name(id='len', ctx=Load()), args=[Str(s='BBB')], keywords=[], 
starargs=None, kwargs=None))], nl=True)])
Sign up to request clarification or add additional context in comments.

Comments

0

Use this regex:

(\w+)\(((?:[^()]*\([^()]*\))*[^()]*)\)

This captures the name of the function in group 1, and the contents the brackets (the parameters) in group 2.

See a live demo of this regex working with your examples.


BTW, Your regex could use some attention:

  • [\w_]+ is equivalent to just \w+ because \w includes underscore
  • [\W\d\w\,] is equivalent to just ., because the combination \W\w (everything not a word char and every word char) includes everything

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.