【问题标题】:Capture all function calls using the python3 re module使用 python3 re 模块捕获所有函数调用
【发布时间】:2021-10-24 08:44:11
【问题描述】:

我有这个字符串和模式:

s = '''double factorial ( double n ) { if ( n == 0 ) { return 1 ; } if ( n == 1 ) {     return factorial(n - 2 + 1) ; } return n * factorial ( n - 1 ) ; }'''
l = re.findall(r"{ .*(factorial\s*\(.*\))", s)

意图是匹配 all fn 调用,即只是 factorial(args) 部分。如何修改上述内容以便列表“l”返回所有相关匹配项?

('l' 当前是 ['factorial ( n - 1 )'] ,这只是 findall 返回后的最后一个匹配项)

【问题讨论】:

  • 为什么在模式中包含{ .*
  • 一般情况下你需要一个解析器来处理这个问题。单独的正则表达式不能很好地处理嵌套内容,例如代码。
  • @mkrieger1 我试图在函数体的左大括号之后进行匹配,可能不需要 ig

标签: python-3.x regex python-re


【解决方案1】:

使用

\bfactorial\s*\([^()]*\)

regex proof

解释

--------------------------------------------------------------------------------
  \b                       the boundary between a word char (\w) and
                           something that is not a word char
--------------------------------------------------------------------------------
  factorial                'factorial'
--------------------------------------------------------------------------------
  \s*                      whitespace (\n, \r, \t, \f, and " ") (0 or
                           more times (matching the most amount
                           possible))
--------------------------------------------------------------------------------
  \(                       '('
--------------------------------------------------------------------------------
  [^()]*                   any character except: '(', ')' (0 or more
                           times (matching the most amount possible))
--------------------------------------------------------------------------------
  \)                       ')'

【讨论】:

    猜你喜欢
    • 2016-06-12
    • 2020-10-02
    • 1970-01-01
    • 2019-01-28
    • 2020-10-10
    • 1970-01-01
    • 2019-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多