且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

有关解析方法签名的正则表达式问题

更新时间:2023-11-12 21:35:22

您无法将可变数量的组与Python正则表达式进行匹配(请参见

You can't match a variable number of groups with Python regular expressions (see this). Instead you can use a combination of regex and split().

>>> name, args = re.match(r'(\w+)\((.*)\)', 'function_name(foo=<str>, bar=<array>, baz=<int>)').groups()
>>> args = [re.match(r'(\w+)=<(\w+)>', arg).groups() for arg in args.split(', ')]
>>> name, args
('function_name', [('foo', 'str'), ('bar', 'array'), ('baz', 'int')])

这将匹配可变数目(包括0)的参数.我选择了不允许额外的空格,但是如果您的格式不是很严格的话,您应该在标识符之间添加\s+来允许它.

This will match a variable number (including 0) arguments. I have chosen not to allow additional whitespace, although you should allow for it by adding \s+ between identifiers if your format isn't very strict.