我正在尝试解析以下字符串:
constructor: function(some, parameters, here) {
使用以下正则表达式:
re.search("(\w*):\s*function\((?:(\w*)(?:,\s)*)*\)", line).groups()
我得到:
('constructor', '')
但我期待的更像是:
('constructor', 'some', 'parameters', 'here')
我错过了什么?
最佳答案
如果您将模式更改为:
print re.search(r"(\w*):\s*function\((?:(\w+)(?:,\s)?)*\)", line).groups()
你会得到:
('constructor', 'here')
这是因为(来自 docs ):
If a group is contained in a part of the pattern that matched multiple times, the last match is returned.
如果您可以一步完成此操作,我不知道如何做。当然,您的选择是执行以下操作:
def parse_line(line):
cons, args = re.search(r'(\w*):\s*function\((.*)\)', line).groups()
mats = re.findall(r'(\w+)(?:,\s*)?', args)
return [cons] + mats
print parse_line(line) # ['constructor', 'some', 'parameters', 'here']
关于Python 正则表达式子组捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29020148/