作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试解析以下字符串:
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/
我是一名优秀的程序员,十分优秀!