好吧,我有這個字串和模式:
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)
意圖是匹配所有fn 呼叫,即僅 factorial(args) 部分。如何修改上述內容,以便串列 'l' 回傳所有相關匹配項?
('l' 當前是 ['factorial ( n - 1 )'] 這只是最后一個匹配,在 findall 回傳之后)
uj5u.com熱心網友回復:
用
\bfactorial\s*\([^()]*\)
請參閱正則運算式證明。
解釋
--------------------------------------------------------------------------------
\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))
--------------------------------------------------------------------------------
\) ')'
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/336645.html
上一篇:使用正則運算式捕獲德國日期格式
