Ala*_*ang 2 python regex abstract-syntax-tree
我试图找到调用函数名称的类名.
例如,假设我有:
class foo1(object):
bar1()
class foo2(object):
bar2()
class foo3(object):
bar3()
Run Code Online (Sandbox Code Playgroud)
如果我正在搜索bar2()我想收到:
class foo2(object):
bar2()
Run Code Online (Sandbox Code Playgroud)
我试过正则表达式class[\s\S]*bar2\(\)(?!class)的想法是,我会对另一个类的外观负面预测.不幸的是,[\ s\S]似乎已经匹配所有内容:https://regex101.com/r/kZ7eE5/1
有没有办法匹配,如果"class"只出现一次匹配所有其他字符(包括新行和制表符)?
也可以接受不需要正则表达式的替代方案.
RE方法可能容易出错(Python语言的表达能力比RE识别的常规语言更强).
使用Python的ast模块来解析Python代码:
code = '''
class foo1(object):
bar1()
class foo2(object):
bar2()
class foo3(object):
bar3()
'''
>>> import ast
>>> tree = ast.parse(code)
>>> for i in tree.body:
... if isinstance(i, ast.ClassDef):
... print('class: %s' % i.name)
...
class: foo1
class: foo2
class: foo3
>>>
Run Code Online (Sandbox Code Playgroud)
你可以做很多其他事情,请查看https://greentreesnakes.readthedocs.org/en/latest/上的文档.
编辑:一个更完整的例子:
>>> for i in tree.body:
... if isinstance(i, ast.ClassDef):
... for j in i.body:
... if isinstance(j, ast.Expr):
... print('found a call to function %s in class %s' % (j.value.func.id, i.name))
...
found a call to function bar1 in class foo1
found a call to function bar2 in class foo2
found a call to function bar3 in class foo3
Run Code Online (Sandbox Code Playgroud)