使用 python3 re 模块捕获所有函数调用
Capture all function calls using the python3 re module
嗯,我有这个字符串和模式:
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' returns 所有相关的匹配项?
('l' 当前是 ['factorial ( n - 1 )'],这只是 findall returns 之后的最后一场比赛 returns)
使用
\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))
--------------------------------------------------------------------------------
\) ')'
嗯,我有这个字符串和模式:
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' returns 所有相关的匹配项?
('l' 当前是 ['factorial ( n - 1 )'],这只是 findall returns 之后的最后一场比赛 returns)
使用
\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))
--------------------------------------------------------------------------------
\) ')'