Python 在数组中保存匹配项

Python 在数组中保存匹配项,python,regex,Python,Regex,我遇到了一个问题,需要检查一个表达式,比如模块名a、b、c、d,然后将这些变量保存到数组中。这就是我到目前为止所得到的: /^module\s(?P<module_name>\w+)(\s?)\(((\s?)((?P<module_params>\w+)\,)?)+(? P<module_last_param>\w+)\)$/ 使用match.groups时: ('hi', '', '', '', 'b,', 'b', 'c') 运行此示例时: modul

我遇到了一个问题,需要检查一个表达式,比如模块名a、b、c、d,然后将这些变量保存到数组中。这就是我到目前为止所得到的:

/^module\s(?P<module_name>\w+)(\s?)\(((\s?)((?P<module_params>\w+)\,)?)+(? P<module_last_param>\w+)\)$/
使用match.groups时:

('hi', '', '', '', 'b,', 'b', 'c')
运行此示例时:

module hi(a, b, c)

但问题是,模块参数的值显然正在被替换,我需要将它们全部保存在一个数组中。

如果要使用正则表达式,请尝试以下操作:

s = 'module hi(a, b, c)'
regex = re.compile(r'\s(\w+)\(([^\)]+)\)')
try:
    module_name, parameters = regex.search(s).groups()
except AttributeError as e:
    print 'No match for: {}'.format(s)
    raise
parameters = parameters.split(',')
print module_name, parameters
d = {'module_name':module_name,
     'module_params':parameters[:-1],
     'module_last_param':parameters[-1]}
print d
# {'module_last_param': ' c', 'module_name': 'hi', 'module_params': ['a', ' b']}
如果您确信所有数据都符合该模式,那么也可以在不使用正则表达式的情况下执行此操作:

name, params = s.split('(')
name = name.split()[1]
params = params[:-1].split(',')
d = {'module_name':name,
     'module_params':params[:-1],
     'module_last_param':params[-1]}

对于那个例子,正确的/期望的输出是什么?我想要像{'module_params':['a','b'],'module_name':'hi','module_last_param':'c'}这样的东西,但是我想这是不可能的,那么{'module_params_1':'a','module_params_2':'b','module u name':'hi module hi and module u last_param':'c'}是好的,你认为我能做什么呢,我试图找到一种只使用第一个正则表达式的方法,但是,这看起来不可能,然后我将使用我的第一个正则表达式进行检查,并按照您的建议使用split来提取参数,一旦优先级为verify the pattern(验证模式)。您可以在这里玩,如果您想制作您的原始作品-最好保持尽可能简单。
name, params = s.split('(')
name = name.split()[1]
params = params[:-1].split(',')
d = {'module_name':name,
     'module_params':params[:-1],
     'module_last_param':params[-1]}