如何将python函数定义(以及其他任何内容)与RegEx相匹配?

Str*_*ngs 2 python regex

我试图在Python中使用RegEx来解析函数定义而忽略其他.我一直遇到问题.RegEx是否适合在这里使用?

def foo():
  print bar
-- Matches --

a = 2
def foo():
  print bar
-- Doesn't match as there's code above the def --

def foo():
  print bar
a = 2
-- Doesn't match as there's code below the def --
Run Code Online (Sandbox Code Playgroud)

我正在尝试解析的字符串示例是"def isPalindrome(x):\n return x == x[::-1]".但实际上可能包含def本身之上或之下的行.

我必须使用什么RegEx表达式才能实现这一目标?

nem*_*emo 6

不,正则表达式不适合这项工作.这类似于人们拼命试图用正则表达式解析HTML.这些语言不规律.因此,您无法解决您将遇到的所有怪癖.

使用内置解析器模块,构建解析树,检查定义节点并使用它们.使用该ast模块甚至更好,因为它更方便使用.一个例子:

import ast

mdef = 'def foo(x): return 2*x'
a = ast.parse(mdef)
definitions = [n for n in ast.walk(a) if type(n) == ast.FunctionDef]
Run Code Online (Sandbox Code Playgroud)