Search code examples
python-3.xregexpython-re

Capture all function calls using the python3 re module


Well I have this string and pattern :

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)

Intent is to match all fn calls i.e just the factorial(args) part. How do I modify the above so that the list 'l' returns all the relevant matches?

('l' is currently ['factorial ( n - 1 )'] which is just the last match, after findall returns)


Solution

  • Use

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

    See regex proof.

    EXPLANATION

    --------------------------------------------------------------------------------
      \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))
    --------------------------------------------------------------------------------
      \)                       ')'