Regex question about parsing method signature

£可爱£侵袭症+ 提交于 2019-11-29 12:06:04
marcog

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!