Regular expression to match function name and all arguments in Python

前端 未结 3 947
囚心锁ツ
囚心锁ツ 2021-01-17 18:20

Suppose I have a string such as the following:

\"func(arg1, arg2, arg3, arg4, ..., argn)\"

EDIT: This function is not in some particular la

相关标签:
3条回答
  • 2021-01-17 18:41

    Looks like you're 90% there, why not just swap the arg and args groupings and do:

    import re
    
    fn_match = re.match(r"(?P<function>\w+)\s?\((?P<arg>(?P<args>\w+(,\s?)?)+)\)", s)
    fn_dict = fn_match.groupdict()
    del fn_dict['args']
    fn_dict['arg'] = [arg.strip() for arg in fn_dict['arg'].split(',')]
    
    0 讨论(0)
  • 2021-01-17 18:51

    To answer the last part of your question: No. Python does not have anything similar to Scheme's "match", nor does it have pattern matching like ML/Haskell. The closest thing it has is the ability to destructure things like this

    >>> (a, [b, c, (d, e)]) = (1, [9, 4, (45, 8)])
    >>> e
    8
    

    And to extract the head and tail of a list (in Python 3.x) like this...

    >>> head, *tail = [1,2,3,4,5]
    >>> tail
    [2, 3, 4, 5]
    

    There are some modules floating around that do real pattern matching in python though, but I can't vouch for their quality.

    If I had to do it, I would implement it a bit differently -- maybe have the ability to input a type and optional arguments (e.g. length, or exact content) and a function to call if it matches, so like match([list, length=3, check=(3, str), func]) and that would match (list _ _ somestr) and call func with somestr in scope, and you could also add more patterns.

    0 讨论(0)
  • 2021-01-17 19:05

    Regular expressions cannot parse complex programming languages.

    If you're just trying to parse Python, I suggest taking a look at the ast module, which will parse it for you.

    0 讨论(0)
提交回复
热议问题