【发布时间】:2015-02-07 01:50:12
【问题描述】:
如何从 python 文件中捕获类和方法?
我不关心 attrs 或 args。
class MyClass_1(...):
...
def method1_of_first_class(self):
...
def method2_of_first_class(self):
...
def method3_of_first_class(self):
...
class MyClass_2(...):
...
def method1_of_second_class(self):
...
def method2_of_second_class(self):
...
def method3_of_second_class(self):
...
到目前为止我尝试了什么:
class ([\w_]+?)\(.*?\):.*?(?:def ([\w_]+?)\(self.*?\):.*?)+?
选项:点匹配换行符
学习课程
Match the characters “class ” literally «class »
Match the regular expression below and capture its match into backreference number 1 «([\w_]+?)»
Match a single character present in the list below «[\w_]+?»
Between one and unlimited times, as few times as possible, expanding as needed (lazy) «+?»
A word character (letters, digits, etc.) «\w»
The character “_” «_»
Match the character “(” literally «\(»
Match any single character «.*?»
Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character “)” literally «\)»
Match the character “:” literally «:»
Match any single character «.*?»
Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
捕获方法:
Match the regular expression below «(?:def ([\w_]+?)\(self.*?\):.*?)+?»
Between one and unlimited times, as few times as possible, expanding as needed (lazy) «+?»
Match the characters “def ” literally «def »
Match the regular expression below and capture its match into backreference number 2 «([\w_]+?)»
Match a single character present in the list below «[\w_]+?»
Between one and unlimited times, as few times as possible, expanding as needed (lazy) «+?»
A word character (letters, digits, etc.) «\w»
The character “_” «_»
Match the character “(” literally «\(»
Match the characters “self” literally «self»
Match any single character «.*?»
Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character “)” literally «\)»
Match the character “:” literally «:»
Match any single character «.*?»
Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
但它只捕获类名和第一个方法,我认为这是因为反向引用编号 2 不能捕获超过 1,即使它在 (?:myregex)+ 内?
电流输出:
'MyClass_1':'method1_of_first_class',
'MyClass_2':'method1_of_second_class'
期望的输出:
'MyClass_1':['method1_of_first_class','method2_of_first_class',...],
'MyClass_2':['method1_of_second_class','method2_of_second_class',...]
【问题讨论】:
-
你的预期输出是什么?
-
[MyClass_1, [method1_of_first_class,method2_of_first_class,...]][MyClass_2, [method1_of_second_class,method2_of_second_class,...]]
标签: regex