正则表达式在使用Python正则表达式的文件中查找函数调用?

2024-05-14 12:46:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我想要一个正则表达式,其中我将与Python re模块一起使用,它将在Python文件中查找Python函数调用,但是在我要查找的函数调用周围会有一些警告。

  • 函数调用将有一个单独的特定名称。
  • 函数调用可以是链式的,但只有一个链式调用始终具有相同的名称。
  • 第一个函数将始终采用单个字符串参数。
  • 然而,链式函数可能会接受任意参数(这是让我担心的)。

下面是我要在文件中查找的函数的示例用法:

# Simple function call.
f("_key")

# The chained function call, in the simplest format (no args).
f("_key").g()

# The chained function call with simple arguments.
f("_key").g("hello", 1337)

# The chained function call with possible, more complex arguments
f("_key").g(obj.blah(), {"dog":"cat"})

# And then the possibility for long function calls to extend over one line
f("_key").g(
            "dogs",
            "cats",
            {"living":"together"})

还有一个常见的免责声明:我做了一个搜索,问题和我很接近,但我想知道我的需求是否受到足够的限制,可以绕过“常规与非常规”的语言问题。这是因为我不是计算机科学专业的学生,害怕正则表达式。


Tags: 文件thekey函数re名称参数with
2条回答

FWIW,这是Grammar/Grammar的摘录:

decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE

trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME

power: atom trailer* ['**' factor]
atom: ('(' [yield_expr|testlist_comp] ')' |
       '[' [listmaker] ']' |
       '{' [dictorsetmaker] '}' |
       '`' testlist1 '`' |
       NAME | NUMBER | STRING+)

arglist: (argument ',')* (argument [',']
                         |'*' test (',' argument)* [',' '**' test] 
                         |'**' test)

这些情况需要由正则表达式处理,以捕获所有函数调用而不出现任何误报。

与其使用regex,不如使用Python标准库附带的工具集之一:

这应该符合您的要求:

[a-zA-Z]+\([^\)]*\)(\.[^\)]*\))?

相关问题 更多 >

    热门问题