[英]How to match multiple multi-line python function definitions separately
我一直在努力编写一个可以匹配我想要的正则表达式。
我希望能够解析整个 python 源文件,并为该文件获取所有函数定义的列表。
我写了一些示例文本来解析,试图考虑 python 函数 def 中可能存在的所有各种复杂性:
def New_function_withSomestuff10(test: str, thing: str,
third: float, last=a(10): int) -> str:
test
def stuff(things):
stuff
def New_function_withSomestuff11(test: str, thing: str,
third: float, last: int) -> str:
test
我有一个当前的 Regex 似乎与这些很好匹配,但它似乎与所有这些匹配:
regex = r'def (?P<name>\w*)\([\s\S]*\):[\s\S]*'
“name”捕获组仅返回“New_function_withSomestuff10”,该捕获组之后的所有内容都会抓取到示例文本的末尾。
我的希望是得到
re.findall(regex, sample_text)
-> ['New_function_withSomestuff10', 'stuff', 'New_function_withSomestuff11']
谁能帮助我理解我做错了什么? 我一直试图围绕贪婪与懒惰量词、前瞻/后视以及其他此类有用的工具进行思考,但它们似乎都没有做我需要的(或者,更有可能的是,我只是错误地使用了它们)。
我希望下面会有所帮助:
regex=r"def (?P<name>\w+)\(.*?\)"
re.findall(regex, sample_text, re.DOTALL)
#['New_function_withSomestuff10', 'stuff', 'New_function_withSomestuff11']
解释:
Regex: def (?P<name>\\w+)\\(.*?\\)
Flag: re.DOTALL
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.