有关解析方法签名的正则表达式问题 [英] Regex question about parsing method signature
问题描述
我正在尝试解析这种格式的方法签名:
I'm trying to parse a method signature that is in this format:
'function_name(foo=<str>, bar=<array>)'
由此,我想要方法的名称,每个参数及其类型.显然我不希望<
,>
字符等.参数的数量将是可变的.
From this, I want the name of the method, and each argument and it's type. Obviously I don't want the <
, >
characters, etc. The number of parameters will be variable.
我的问题是:使用此正则表达式时如何获取所有参数?我正在使用Python,但我只是在寻找一个一般的想法.我是否需要命名组,如果需要,我如何使用它们来捕获多个参数,每个参数都有其类型,都在一个正则表达式中?
My question is: How is it possible to get all the parameters when using this regex? I'm using Python, but I'm just looking for a general idea. Do I need named groups and, if so, how can I use them to capture multiple parameters, each with it's type, all in one regex?
推荐答案
您无法将可变数量的组与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.
这篇关于有关解析方法签名的正则表达式问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!